Detect system architecture (x86/x64) while running
Is it possible to detect the system/processor architecture while the program is runni开发者_StackOverflowng (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;
}
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.
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
You can also use Processor macros to detect system architecture in c++ code, for example:
#include <iostream>
int main()
{
#ifdef __x86_64__
std::cout << "x86" << std::endl;
#endif
#ifdef __arm__
std::cout << "arm" << std::endl;
#endif
}
Here is a reference list of Pre-defined Compiler Macros.
EDIT:Processor macros is compiler-independant, different compilers have different Processor macros, So it is not possible to detect system architecture this way.
精彩评论