我正在尝试以下操作,在 win32 上使用 gcc。
#include <stdio.h>
struct st { char c; int x; } __attribute__ ((packed));
int main() {
printf("%d\n", sizeof(struct st));
return 0;
}
我期望打印的值为 5,但实际是 8。
但是,通过以下内容,我得到 5。
#include <stdio.h>
#pragma pack(1)
struct st { char c; int x; };
int main() {
printf("%d\n", sizeof(struct st));
return 0;
}
我的程序一定有问题,但我看不出问题出在哪里。 我已阅读gcc's manual以及关于此的几个问题,我仍然感到困惑。有什么提示吗?
另外,从对这些问题的回答中,我明白我不应该将打包结构用于 marshalling ,我可能不会经常使用它,但我仍然想了解在这么短的程序中我看不到什么。
注意:gcc-4.9.2 和 gcc-4.8.4 都会出现此问题。
最佳答案
您将该属性放在了错误的位置 - 试试这个:
struct st { char c;
int x __attribute__ ((packed));
};
根据 gcc 手册中的示例,这将导致 x
被打包,使其紧跟在 c
之后。
当然,您一开始就不应该这样做,因为您的代码在某些架构上会崩溃,即使没有崩溃,也可能会造成性能损失。
关于c - 我是否误解了 GCC 中的 __attribute__ ((packed)) ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27839287/