Is it possible to detect the system/processor architecture while the program is running (under windows and under linux) in c++?
On Windows, you may use __cpuid
. On Linux, you can open("/proc/cpuinfo")
and look through it.
Here is an example on Windows, based on the example in the MSDN page:
#include <intrin.h>
bool cpuSupports64()
{
int CPUInfo[4];
__cpuid(CPUInfo, 0);
return (CPUInfo[3] & 0x20000000) || false;
}
All software approaches will only give you the architecture of the OS you are using. If you are using a 32-bit OS on a 64-bit Hardware, that is what you will get. Among the software approaches are the size of a pointer, the size of a Integer data type or a Float data type. On Linux, you can do a 'uname -a'.
Use GetSystemInfo() or GetNativeSystemInfo() functions under Windows depending on your purpose. I don't know how to do it on Linux though.
Depending on what you intend to do with this information (e.g. select the fastest handcoded assembly code for a specific CPU), under Linux you might want to read /proc/cpuinfo, specifically: the "flags" section, so you can choose between SSE/SSE2 implementation vs. MMX implementation vs. whatever.
Big endian system vs. little endian system is a bit more complicated, refer to: http://en.wikipedia.org/wiki/Endianess
Under Linux, you can use the uname
system call. It fills in this user-allocated struct:
struct utsname { char sysname[]; /* Operating system name (e.g., "Linux") */ char nodename[]; /* Name within "some implementation-defined network" */ char release[]; /* OS release (e.g., "2.6.28") */ char version[]; /* OS version */ char machine[]; /* Hardware identifier */ #ifdef _GNU_SOURCE char domainname[]; /* NIS or YP domain name */ #endif };
The machine
field will identify the architecture.