6

I want to compile part of my code only on x86 and x86_64 linux, but not s390 linux or others. How to use the macro define in C to achieve it? I know linux is to determine linux OS, and 386, 486 and 586 to determine CPU architecture. Is there an easy macro define to determine x86 linux and x86_64 linux? Thanks

Mr Lister
  • 44,061
  • 15
  • 107
  • 146
JackChen255
  • 305
  • 1
  • 4
  • 11

2 Answers2

17

You can detect whether or not you are in a 64 bit mode easily:

#if defined(__x86_64__)
/* 64 bit detected */
#endif
#if defined(__i386__)
/* 32 bit x86 detected */
#endif
David Hoelzer
  • 15,359
  • 4
  • 43
  • 65
  • Hi David, I need to detect linux 86 and linux 8664. Your solution can detect 8664 and i386. But how about i486 and i584 and other x86 platforms? Do I need to write it as #if defined(__i386__) || #if defined(__i486__) || #if defined(__i586__) ? – JackChen255 May 10 '15 at 18:12
  • 1
    Well, i386 will be true of all 32 bit Intel based Linux installs. If you'd like to dig deeper you can. For example, __amd64__ would indicate a 64 bit system on an AMD architecture. Itanium would be __IA64__. __486__, __586__ and __686__ also do what you would expect. You might want to look at this: http://sourceforge.net/p/predef/wiki/Architectures/ – David Hoelzer May 11 '15 at 01:12
2

If your compiler does not provide pre-defined macros and constants, you may define it yourself: gcc -D WHATEVER_YOU_WANT.

Additional reward: if you compile your code for, say, amd64, but you don't define amd64, you can compare the results (the version which use amd64-specific parts vs the generic version) and see, whether your amd64 optimalization worths the effort.

ern0
  • 3,110
  • 24
  • 35