Detecting CPU architecture compile-time


What is the most reliable way to find out CPU architecture when compiling C or C++ code? As far as I can tell, different compilers have their own set of non-standard preprocessor definitions (_M_X86 in MSVS, __i386__, __arm__ in GCC, etc).

Is there a standard way to detect the architecture I'm building for? If not, is there a source for a comprehensive list of such definitions for various compilers, such as a header with all the boilerplate #ifdefs?

10/18/2018 3:22:15 PM

Accepted Answer

Here is some information about Pre-defined Architecture Macros and other types of pre-defined macros.

This question asks where they are defined in the GCC source code.

4/19/2018 10:43:29 PM

There's no inter-compiler standard, but each compiler tends to be quite consistent. You can build a header for yourself that's something like this:

#if MSVC
#ifdef _M_X86
#define ARCH_X86

#if GCC
#ifdef __i386__
#define ARCH_X86

There's not much point to a comprehensive list, because there are thousands of compilers but only 3-4 in widespread use (Microsoft C++, GCC, Intel CC, maybe TenDRA?). Just decide which compilers your application will support, list their #defines, and update your header as needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow