Detecting CPU architecture compile-time Detecting CPU architecture compile-time c c

Detecting CPU architecture compile-time


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#endif#endif#if GCC#ifdef __i386__#define ARCH_X86#endif#endif

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.


If you would like to dump all available features on a particular platform, you could run GCC like:

gcc -march=native -dM -E - </dev/null

It would dump macros like #define __SSE3__ 1, #define __AES__ 1, etc.


If you want a cross-compiler solution then just use Boost.Predef which contains

  • BOOST_ARCH_ for system/CPU architecture one is compiling for.
  • BOOST_COMP_ for the compiler one is using.
  • BOOST_LANG_ for language standards one is compiling against.
  • BOOST_LIB_C_ and BOOST_LIB_STD_ for the C and C++ standard library in use.
  • BOOST_OS_ for the operating system we are compiling to.
  • BOOST_PLAT_ for platforms on top of operating system or compilers.
  • BOOST_ENDIAN_ for endianness of the os and architecture combination.
  • BOOST_HW_ for hardware specific features.
  • BOOST_HW_SIMD for SIMD (Single Instruction Multiple Data) detection.

For example

#if defined(BOOST_ARCH_X86)    #if BOOST_ARCH_X86_64        std::cout << "x86_64 " << BOOST_ARCH_X86_64 << " \n";    #elif BOOST_ARCH_X86_32        std::cout << "x86 " << BOOST_ARCH_X86_32 << " \n";    #endif#elif defined(BOOST_ARCH_ARM)    #if _M_ARM        std::cout << "ARM " << _M_ARM << " \n";    #elif _M_ARM64        std::cout << "ARM64 " << _M_ARM64 << " \n";    #endif#endif

You can find out more on how to use it here