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
Asked
Active
Viewed 9,956 times
6
-
This isn't clear; x86 is the hardware platform, not the operating system... – Oliver Charlesworth May 09 '15 at 12:37
-
2With 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
-
Possible 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
2 Answers
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
-
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
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