一、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