gcc #pragma 与__attribute

本文详细介绍了GCC编译器中的两种对齐方式:#pragma pack和__attribute__((aligned)),并通过示例程序展示了不同对齐设置下结构体大小的变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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",
  sizeof(aa),sizeof(bb),sizeof(cc),
  sizeof(dd),sizeof(ee),sizeof(ff));
printf("%d,%d,%d,%d,%d,%d\n",
  sizeof(mm),sizeof(nn),sizeof(oo),
  sizeof(pp),sizeof(qq),sizeof(rr));

return 0;
}


程序运行结果是
[root@A09 joke]#  ./a.out8,6,6,8,8,8
6,8,12,8,8,64
这样看来,这两种用法已经比较清楚了,但是gcc手册中说了不建议使用#pragma,而且#pragma最多只能支持16字节的对齐,后者在没有查到资料的情况下,我做了个测试,最多可以支持8192字节的对齐
由于不同编译器可能对对齐的实现有区别,在不同编译器编译的程序间进行数据传递就有可能要用到这些东西了,当然,还有其他的用处

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值