GCC:对齐设置 __attribute__ 和 #pragma
GCC: Alignment settings with __attribute__ and #pragma
如何将 #pragma pack(2)
定义为结构属性?
我读过 here __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)))
添加到每个结构成员,因为它可用于为每个成员单独设置对齐方式。
如何将 #pragma pack(2)
定义为结构属性?
我读过 here __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)))
添加到每个结构成员,因为它可用于为每个成员单独设置对齐方式。