c - 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!!!
解决方案
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
推荐阅读
- rxjs - rxjs 检查 outerobservable 不为空,然后才订阅内部 observable
- flutter - 如何在颤动中实现以下小部件?
- vue.js - 如何验证多个文件的最大文件大小为每个文件 2 mb?(验证)
- c++ - C++ 变量等于非变量
- powershell - Powershell 团队消息多行
- android - 此版本符合 Google Play 64 位要求本机应用程序
- laravel-5 - Mews\Purifier\Purifier::__construct() 必须是 Illuminate\Filesystem\Filesystem 的实例
- akka - 在 Akka 中是否可以像使用 RxJava/Reactor compose 一样从 Source=>Source 函数创建流?
- assembly - 对 X86 分割感到困惑
- extjs - 我是 EXT-JS 的新手,任何人都可以帮助我们哪种方法更适合电子邮件的自定义验证?