Bjoern Bjoern - 1 year ago 75
C Question

How to identify a 64 Bit build on Linux using the preprocessor?

I am about to port a Windows 32 Bit application to 64 Bit, but might decide to port the whole thing to Linux later.

The code contains sections which are dependent on the amount of memory available to the application (which depends on whether I'm creating a 32 or 64 Bit build), while the ability to compile a 32 Bit version of the code should be preserved for backward compatibility.

On Windows, I am able to simply wrap the respective code sections into preprocessor statements to ensure the right version of the code is compiled.

Unfortunately I have very few experience on programming on the Linux platform, so the question occurred:

How am I able to identify a 64 Bit build on the Linux platform?

Is there any (preferably non-compiler-specific) preprocessor define I might check for this?

Thanks in advance!


Answer Source

Assuming you are using a recent GNU GCC compiler for IA32 (32-bit) and amd64 (the non-Itanium 64-bit target for AMD64 / x86-64 / EM64T / Intel 64), since very few people need a different compiler for Linux (Intel and PGI).

There is the compiler line switch (which you can add to CFLAGS in a Makefile) -m64 / -m32 to control the build target.

For conditional C code:

#if defined(__LP64__) || defined(_LP64)
#define BUILD_64   1


#include <limits.h>
#if ( __WORDSIZE == 64 )
#define BUILD_64   1

While the first one is GCC specific, the second one is more portable, but may not be correct in some bizarre environment I cannot think of.

At present both should both work for IA-32 / x86 (x86-32) and x86-64 / amd64 environments correctly. I think they may work for IA-64 (Itanium) as well.

Also see Andreas Jaeger's paper from GCC Developer's Summit entitled, Porting to 64-bit GNU/Linux Systems which described 64-bit Linux environments in additional detail.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download