#pragma pack(n)和__attribute__((aligned(m)))的区别:
#include<stdio.h>
#pragma pack(4)
typedef struct{
uint32_t f1;
uint8_t f2;
uint8_t f3;
uint32_t f4;
uint64_t f5;
}__attribute__((aligned(1024))) ts;
int main()
{
printf("Struct size is: %d, aligned on 1024\n",sizeof(ts));
printf("Allocate f1 on address: 0x%x\n",&(((ts*)0)->f1));
printf("Allocate f2 on address: 0x%x\n",&(((ts*)0)->f2));
printf("Allocate f3 on address: 0x%x\n",&(((ts*)0)->f3));
printf("Allocate f4 on address: 0x%x\n",&(((ts*)0)->f4));
printf("Allocate f5 on address: 0x%x\n",&(((ts*)0)->f5));
return 0;
}
输出:
Struct size is: 1024, aligned on 1024
Allocate f1 on address: 0x0
Allocate f2 on address: 0x4
Allocate f3 on address: 0x5
Allocate f4 on address: 0x8
Allocate f5 on address: 0xc
注意
绿色部分表明了__attribute__((aligned(1024))) 的作用
红色部分说明#pragma pack(4)只对大小大于4的成员变量的地址偏移起作用
紫色部分说明对于大小大于4的成员变量,其地址偏移按照4字节对齐