Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect if I'm compiling for a 64bits architecture in C++

In a C++ function I need the compiler to choose a different block if it is compiling for a 64 bit architecture.

I know a way to do it for MSVC++ and g++, so I'll post it as an answer. However I would like to know if there is a better way (more elegant that would work for all compilers/all 64 bits architectures). If there is not a better way, what other predefined macros should I look for in order to be compatible with other compiler/architectures?

like image 977
Mathieu Pagé Avatar asked Sep 06 '25 03:09

Mathieu Pagé


1 Answers

An architecture-independent way to detect 32-bit and 64-bit builds in C and C++ looks like this:

// C
#include <stdint.h>

// C++
#include <cstdint>

#if INTPTR_MAX == INT64_MAX
// 64-bit
#elif INTPTR_MAX == INT32_MAX
// 32-bit
#else
#error Unknown pointer size or missing size macros!
#endif
like image 196
DarkDust Avatar answered Sep 07 '25 22:09

DarkDust