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
-
This isn't clear; x86 is the hardware platform, not the operating system... – Oliver Charlesworth May 09 '15 at 12:37
-
3With GCC you can use this `gcc -dM -E - < /dev/null` to display all the macros. – Galik May 09 '15 at 12:50
-
You know, I think I just figured that name out.. Are you saying x86_64?? – David Hoelzer May 09 '15 at 14:43
-
[Detecting CPU architecture compile-time](http://stackoverflow.com/q/152016/995714) – phuclv May 09 '15 at 14:55
-
1Possible duplicate of [Detecting CPU architecture compile-time](https://stackoverflow.com/questions/152016/detecting-cpu-architecture-compile-time) – phuclv Sep 15 '18 at 11:33
-
Possible duplicate of [Detecting 64bit compile in C](https://stackoverflow.com/q/5272825/995714) – phuclv Sep 15 '18 at 11:33
3 Answers
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

- 15,862
- 4
- 48
- 67
-
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
-
1Well, 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
-
Is there a way to detect either without just checking both with `||`? – Aaron Franke Jun 05 '22 at 18:49
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.

- 3,074
- 25
- 40
Another option instead of pre-processor macros is sizeof(void*) == 4
to detect 32-bit and/or sizeof(void*) == 8
for 64-bit. This is more portable, as it does not rely on any defined symbols or macros.
As long as your compiler has any level of optimization enabled, it should be able to see that this kind of statement is either always true or always false for the current build target, so the resulting binary should be no less efficient than if you'd used pre-processor macros.

- 366
- 3
- 10