当前位置: 技术问答>linux和unix
请教,GCC如何将struct alignment设置成为字节对齐啊?
来源: 互联网 发布时间:2015-04-21
本文导语: 现在有一个结构,由于gcc默认是8字节对齐,导致结构字段的实际地址和理论地址不一致,谁知到那个选项可以控制对齐啊?谢谢了 | 见本版FAQ: 请问在linux下编译程序怎么设置编译器字节对...
现在有一个结构,由于gcc默认是8字节对齐,导致结构字段的实际地址和理论地址不一致,谁知到那个选项可以控制对齐啊?谢谢了
|
见本版FAQ: 请问在linux下编译程序怎么设置编译器字节对齐?
http://expert.csdn.net/Expert/FAQ/FAQ_Index.asp?id=175563
http://expert.csdn.net/Expert/FAQ/FAQ_Index.asp?id=175563
|
FAQ里的是MS'style的,下面才是gcc的:
#include
#pragma pack(1) /* one byte */
typedef struct {
char a;
short b;
} problemthing;
#pragma pack() /* return to default */
typedef struct {
char a;
short b;
} problemthing1;
int main()
{
printf("size of pro is %dn", sizeof(problemthing));
printf("size of pro is %dn", sizeof(problemthing1));
return 0;
}
#include
#pragma pack(1) /* one byte */
typedef struct {
char a;
short b;
} problemthing;
#pragma pack() /* return to default */
typedef struct {
char a;
short b;
} problemthing1;
int main()
{
printf("size of pro is %dn", sizeof(problemthing));
printf("size of pro is %dn", sizeof(problemthing1));
return 0;
}
|
Use this keyword __attribute__((packed)
#include
int main()
{
struct {
char a;
int b;
char c;
} __attribute__((packed)) M;
printf("%dn", &M.c - &M.a);
return 0;
}
the output is 5, means 1byte for a, 4 byte for b.
if you don't use this keyword, the output is 8, means 4 byte for a (not aligned in 1 byte), 4 byte for b
#include
int main()
{
struct {
char a;
int b;
char c;
} __attribute__((packed)) M;
printf("%dn", &M.c - &M.a);
return 0;
}
the output is 5, means 1byte for a, 4 byte for b.
if you don't use this keyword, the output is 8, means 4 byte for a (not aligned in 1 byte), 4 byte for b
|
#pragma pack(1)