views:

911

answers:

7

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?

Thanls,

+1  A: 

This works for MSVC++ and g++ :

#if defined(_M_X64)) || defined(__amd64__)
  // code...
#endif
Mathieu Pagé
+7  A: 

Raymond covers this.

GSerg
+1  A: 

Here's a good overview for Mac OS X:

http://developer.apple.com/documentation/Darwin/Conceptual/64bitPorting

mike511
A: 

If you're compiling for the Windows platform, you should use:

#ifdef _WIN64

The MSVC compiler defines that for both x64 and ia64 platforms (you don't want to cut out that market, do you?). I'm not sure if gcc does the same - but it should if it doesn't.

An alternative is

#ifdef WIN64

which has a subtle difference. WIN64 (without the leading underscore) is defined by the SDK (or the build configuration). Since this is defined by the SDK/build config, it should work just as well with gcc.

Michael Burr
A: 
#ifdef _LP64

Works on both platforms

A: 

Similar question asked here on SO... with a really great answer.

ceretullis
+5  A: 

Why are you choosing one block over the other? If your decision is based on the size of a pointer, use sizeof(void*) == 8. If your decision is based on the size of an integer, use sizeof(int) == 8.

My point is that the name of the architecture itself should rarely make any difference. You check only what you need to check, for the purposes of what you are going to do. Your question does not cover very clearly what your purpose of the check is. What you are asking is akin to trying to determine if DirectX is installed by querying the version of Windows. You have more portable and generic tools at your disposal.

flodin
sizeof(int) isn't good example. It depends on compiler. I tried on 64 bit linux with g++ and it was 4 bytes long. Better use sizeof(void*) to determine architecutre. But im not sure if it is the same on all machines.
klew
@klew, I think you missed flodin's point: "You check only what you need to check, for the purposes of what you are going to do."
mxp