FROM:http://www.lslnet.com/linux/dosc1/03/linux-120104.htm
在使用gcc的时候,特别是阅读源码的时候会看到
#pragma pack(n)
#pragma pack()
和
__attribute((aligned (8)))
__attribute__ ((packed));
下面写一下我的一点认识,不一定对,欢迎指正
这两种方式是gcc的c扩展,用来对齐的,包括栈对齐,变量地址对齐内存分配对齐,这几种方式一般来说gcc是兼容的
#pragma pack(n)
n的取值可以为1、2、4、8、16,在编译过程中按照n个字结对齐
#pragma pack()
取消对齐,按照编译器的优化对齐方式对齐
__attribute__ ((packed));
是说取消结构在编译过程中的优化对齐。
__attribute__ ((aligned (n)));
让所作用的成员对齐在n字节自然边界上,如果结构中有成员的长度大于n,则按照最大成员的长度来对齐
我写了一个小测试程序来测验 struct a
{
int a;
char b;
char c;
}aa;
#pragma pack(1)
struct b
{
int a;
char b;
char c;
}bb;
#pragma pack()
#pragma pack(2)
struct c
{
int a;
char b;
char c;
}cc;
#pragma pack()
#pragma pack(4)
struct d
{
int a;
char b;
char c;
}dd;
#pragma pack()
#pragma pack(8)
struct e
{
int a;
char b;
char c;
}ee;
#pragma pack()
#pragma pack(16)
struct f
{
int a;
char b;
char c;
}ff;
#pragma pack()
struct m
{
int a;
char b;
char c;
}__attribute__((packed)) mm;
struct n
{
int a;
char b;
}__attribute__((aligned(1))) nn;
struct o
{
long long a;
char b;
char c;
}__attribute__((aligned(2))) oo;
struct p
{
int a;
char b;
char c;
}__attribute__((aligned(4))) pp;
struct q
{
int a;
char b;
char c;
}__attribute__((aligned(8))) qq;
struct r
{
int a;
char b;
char c;
}__attribute__((aligned(8*1024))) rr;
int main()
{
printf("%d,%d,%d,%d,%d,%d\n",
printf("%d,%d,%d,%d,%d,%d\n",
return 0;
}
程序运行结果是
[root@A09 joke]#
6,8,12,8,8,64
这样看来,这两种用法已经比较清楚了,但是gcc手册中说了不建议使用#pragma,而且#pragma最多只能支持16字节的对齐,后者在没有查到资料的情况下,我做了个测试,最多可以支持8192字节的对齐
由于不同编译器可能对对齐的实现有区别,在不同编译器编译的程序间进行数据传递就有可能要用到这些东西了,当然,还有其他的用处