attribute 用法挺多的,网上资料也挺多,大家可以自己搜搜。
我这里主要讲两个较为有用的
1. attribute((packed)) 让结构体等变得 紧凑
这个作用是最小化,尤其用在结构体里面。
struct temp{
int a;
int b;
char c;
};
这个大小不用说: 12个字节
但如果
struct temp{
int a;
int b;
char c;
}__attribute__((packed));
这个大小将会是 : 9 个字节
2.attribute((aligned )) 对齐
struct temp{
int a;
int b;
char c;
};
这个计算下大小: 会是 12;
struct temp{
int a;
int b;
char c;
}__attribute__((aligned(8))) ;
这个你计算下,将会得到 16;
解释下: 这个对齐 将超出的,会再倍算。 12 > 8 ,但小于 2 * 8
故而会占用 16个字节