pragma pack与__attribute__区别

本文详细解析了C语言中结构体对齐的两种方法:使用pragmapack(n)控制成员变量对齐,以及使用__attribute__((aligned(m)))设置结构体整体对齐。通过示例代码展示了不同对齐方式对内存占用的影响。

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

一、pragma pack(n):告诉编译器结构体或类内部的成员变量相对于第一个变量的地址的偏移量的对齐方式,缺省情况下,编译器按照自然边界对齐,当变量所需的自然对齐边界比n大 时,按照n对齐


二、__attribute__((aligned(m))):告诉编译器一个结构体或者类或者联合或者一个类型的变量(对象)分配地址空间时的地址对齐方式。
也就是说,如 果将__attribute__((aligned(m)))作用于一个类型,那么该类型的变量在分配地址空间时,其存放的地址一定按照m字节对齐(m必 须是2的幂次方)。
__attribute__((aligned(m)))也可以作用于一个单独的变量。


注: pragma作用于结构内的成员变量;attribute ((aligned(n)))作用于结构体分配地址的对齐方式

__attribute__ ((__packed__))关键字,它可以做到让我们的结构体,按照紧凑排列的方式,取消编译器对齐优化。

2.1 __attribute__((aligned(m))) 与占用内存大小,见如下代码:

 

 #include<stdio.h>

 #include<stdio.h>

#pragma pack(2)

typedef struct{

char f2;

int f3;

}ST3;  //ST3各成员变量2字节对齐

#pragma pack()

//////////////////////////////////////////////////////////


typedef int more_aligned_int __attribute__((aligned(16)));//more_aligned_int 16字节对齐,sizeof=4
typedef int __attribute__((aligned(16))) more_aligned_int_1 ;//more_aligned_int__1 16字节对齐,sizeof=4....但是 more_aligned_int 代表的意思 != more_aligned_int_1

typedef struct{
	int a;
	char b;
} __attribute__((aligned(64))) ST2;//ST2起始地址64字节对齐,sizeof(ST2)=64

typedef struct{
	int a;
	char b;
} ST1 __attribute__((aligned(64)));//ST1起始地址64字节对齐,sizeof(ST1)=8,所以不能定义ST1结构体数组(数组要求地址连续)

///////////////////////////////////////////////////////////
int main()
{
	//ST1 st1[3];//error: alignment of array elements is greater than element size
	ST1 st1;	
	ST2 st2;
	ST3 st3;
	printf("sizeof st1 =%u,sizeof st2 =%u,sizeof st3=%u,sizeof int_1=%d\n",sizeof(st1),sizeof(st2),sizeof(st3),sizeof(more_aligned_int_1));//8,64,6(重新定义结构体按新方式对齐),4
	return 0;
}

 



原文:https://blog.youkuaiyun.com/minyuanxiani/article/details/82626919  
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值