如何在gcc的编译时识别x86与x86_64?

时间:2021-08-12 05:30:43

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

我想仅在x86和x86_64 linux上编译我的部分代码,而不是s390 linux或其他。如何在C中使用宏定义来实现呢?我知道linux是确定linux OS,而386,486和586确定CPU架构。是否有一个简单的宏定义来确定x86 linux和x86_64 linux?谢谢

2 个解决方案

#1


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

您可以轻松检测是否处于64位模式:

#if defined(__x86_64__)
/* 64 bit detected */
#endif
#if defined(__i386__)
/* 32 bit x86 detected */
#endif

#2


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

如果您的编译器没有提供预定义的宏和常量,您可以自己定义: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.

额外的奖励:如果你编译你的代码,比如amd64,但你没有定义amd64,你可以比较结果(使用amd64特定部分的版本与通用版本),看看你的amd64优化值是否值得努力。

#1


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

您可以轻松检测是否处于64位模式:

#if defined(__x86_64__)
/* 64 bit detected */
#endif
#if defined(__i386__)
/* 32 bit x86 detected */
#endif

#2


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

如果您的编译器没有提供预定义的宏和常量,您可以自己定义: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.

额外的奖励:如果你编译你的代码,比如amd64,但你没有定义amd64,你可以比较结果(使用amd64特定部分的版本与通用版本),看看你的amd64优化值是否值得努力。