4

Possible Duplicate:
Detecting 64bit compile in C

I want my program to run on both 32 bit and 64 bit Linux OS. So In my C code, I want the compiler to know when it is compiling for a 32 bit and 64 bit architecture. So, I need something like that

#ifdef X64
...
#else
...
#endif

Is there any such define in gcc?

Community
  • 1
  • 1
MetallicPriest
  • 29,191
  • 52
  • 200
  • 356
  • What parts of your code have to be different depending on whether you're on a 32-bit or 64-bit system? Can you modify it so it doesn't care? For example, if you need an integer type of a particular width, take a look at ``. – Keith Thompson Aug 04 '11 at 15:51
  • @KeithThompson - it's not only about the integers (which sucks in C/C++, and even after `` - MSVC, anyone?). For example you may have a general piece of code, which has to choose different libraries loaded at runtime through `dlopen`... Of course you can go with `sizeof(void*)`, as far as it gets you. – Tomasz Gandor Aug 08 '14 at 18:44
  • @TomaszGandor: I don't know what you're saying "sucks", but this probably isn't the place to discuss it. In any case, the meaning of "32-bit" and "64-bit" when applied to systems is not at all clear. The OP probably needs to distinguish between x86 and x86_64 architectures. Choosing which library to open is a more complex question than 32-bit vs. 64-bit. – Keith Thompson Aug 08 '14 at 18:47
  • 1
    @KeithThompson - you're right - it was probably about just distinguishing i386 from amd64 (they come under different names, i don't like underscores;) What sucks? For example this: http://stackoverflow.com/questions/126279/c99-stdint-h-header-and-ms-visual-studio You may think: "What's the big deal?". Well, if you're writing an application - nothing, just use the newer compiler. But - men sometimes write libraries. And a library needs to work with compiler across the board. You need to work without `` until the last user of VS 2008 dies... – Tomasz Gandor Aug 08 '14 at 19:05
  • @TomaszGandor: If `` is missing, you can provide your own, as mentioned in [the accepted answer] to that question as well as [here](http://www.lysator.liu.se/(nobg)/c/q8/index.html). (Blame Microsoft, not C or C++.) – Keith Thompson Aug 08 '14 at 19:08

3 Answers3

11

I know of these:

__i386__    
__x86_64__  

I don't know how reliable they are.

The best option would be adding -DMY_32BIT to the Makefile's compile line when compiling for 32 bits and checking for MY_32BIT on your code. That way you can be sure.

Vinicius Kamakura
  • 7,665
  • 1
  • 29
  • 43
4

There is __WORDSIZE in limits.h:

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

This is relatively portable (due to POSIX), but may fail in obscure environments or on windows.

ckruse
  • 9,642
  • 1
  • 25
  • 25
3

Look here:

#ifdef __x86_64
...
#endif
Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171