首页 > 解决方案 > Is __attribute__((packed)) GCC only, or cross platform?

问题描述

Is __attribute__((packed)) GCC only, or cross platform?

If it's GCC only, how can I check if I am compiling on GCC?

So I can do this for a cross-platform packed structure:

#if /*COMPILING_ON_GCC*/
#   define Packed __attribute__((packed))
#else
#   define Packed
#endif

struct MyStruct {
    char A;
    int B;
    long C;
    //...
} Packed;

If it's GCC, Packed will be replaced with __attribute__((packed)), and if it's not, it will be replaced with nothing, and not cause any problems.

BTW I LOVE POUND DEFINE MACROS!!!

标签: cgcc

解决方案


gcc 和 clang 支持它,但它不是 C 标准的一部分,其他编译器不一定支持它。例如,MSVC 没有。

其他编译器可能会使用不同的语法提供类似的功能,例如#pragma pack. 但是没有一种方法可以在任何地方都有效。

您可以在godbolt上尝试一些示例。

__GNUC__您可以通过测试是否定义了宏来确定是否使用 gcc 进行编译。见https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html#Common-Predefined-Macros

#ifdef __GNUC__
#define Packed __attribute__((packed));
#else
#define Packed /* nothing */
#endif

推荐阅读