Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect system architecture (x86/x64) while running

Is it possible to detect the system/processor architecture while the program is running (under windows and under linux) in c++?


2 Answers

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;
}
like image 56
Hosam Aly Avatar answered Jan 03 '26 08:01

Hosam Aly


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.

like image 31
David Joyner Avatar answered Jan 03 '26 08:01

David Joyner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!