![](/img/trans.png)
[英]Is gcc's __attribute__((packed)) / #pragma pack unsafe?
[英]GCC: Alignment settings with __attribute__ and #pragma
如何将#pragma pack(2)
定义为结构属性?
我在这里阅读了 __attribute__((packed,aligned(4)))
大致等效于#pragma pack(4)
。
但是,如果我尝试使用它(至少使用2而不是4),则会得到不同的结果。 例:
#include <stdio.h>
#pragma pack(push, 2)
struct test1 {
char a;
int b;
short c;
short d;
};
struct test1 t1;
#pragma pack(pop)
struct test2 {
char a;
int b;
short c;
short d;
} __attribute__((packed,aligned(2)));
struct test2 t2;
#define test(s,m) printf(#s"::"#m" @ 0x%04x\n", (unsigned int ((char*)&(s.m) - (char*)&(s)))
#define structtest(s) printf("sizeof("#s")=%lu\n", (unsigned long)(sizeof(s)))
int main(int argc, char **argv) {
structtest(t1);
test(t1,a);
test(t1,b);
test(t1,c);
test(t1,d);
structtest(t2);
test(t2,a);
test(t2,b);
test(t2,c);
test(t2,d);
}
输出为(在x86或x86x64,Linux,gcc 4.8.4上编译):
sizeof(t1)=10
t1::a @ 0x0000
t1::b @ 0x0002
t1::c @ 0x0006
t1::d @ 0x0008
sizeof(t2)=10
t2::a @ 0x0000
t2::b @ 0x0001
t2::c @ 0x0005
t2::d @ 0x0007
成员b,c和d的地址在两种情况下都不相同。
我还要添加另一个__attribute__
吗? 我什至在gcc文档中都找不到关于这些属性的精细文档。
正如@Nominal Animal在评论中指出的那样,解决方案是将__attribute__((__aligned__(s)))
到每个struct成员,因为它可用于分别为每个成员设置对齐方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.