gcc推荐的结构体对齐指令
__attribute__((packed))
__attribute__((aligned(n)))
举例说明其用法
(1) “__attribute__((packed))”使用时直接放在要进行内存对齐的类型定义的后面,然后它起作用的范围只有加了这个东西的这一个类型。packed的作用就是取消对齐访问。
#include <stdio.h>
struct mystruct1 // 使用默认的4字节对齐(32位编译器)
{ // 1字节对齐(无对齐) 4字节对齐
int a; // 4 4
char b; // 1 2(1+1)
short c; // 2 2
};
//使用__attribute__((packed))取消对齐
struct mystruct11
{ // 1字节对齐 4字节对齐
int a; // 4 4
char b; // 1 2(1+1)
short c; // 2 2
}__attribute__((packed));
int main(void)
{
printf("sizeof(struct mystruct1) = %d.\n", sizeof(struct mystruct1)); //默认对齐时是8字节