__attribute__ ((aligned (n), packed))
来源:互联网 发布:欧美流行歌手知乎 编辑:程序博客网 时间:2024/06/06 07:06
__attribute__ 的语法为:
__attribute__ ((语法列表))
参数aligned(number) [number为最小对齐的字节数]是用得较多的一个。
另一个是参数packed 表示“使用最小对齐”方式,即对变量是字节对齐,对于域是位对齐。
这个例子稍长了点,不过非常简单:
[root@Kendo develop]# cat align.c
#include <stdio.h>
struct A{
char a; //1Byte
int b; //4B
unsigned short c;//2B
long d; //4B
unsigned longlong e; //8B
char f; //1B
};
struct B{
char a;
int b;
unsigned short c;
long d;
unsigned longlong e;
char f;
}__attribute__((aligned));
struct C{
char a;
int b;
unsigned short c;
long d;
unsigned longlong e;
char f;
}__attribute__((aligned(1)));
struct D{
char a;
int b;
unsigned short c;
long d;
unsigned longlong e;
char f;
}__attribute__((aligned(4)));
struct E{
char a;
int b;
unsigned short c;
long d;
unsigned longlong e;
char f;
}__attribute__((aligned(8)));
struct F{
char a;
int b;
unsigned short c;
long d;
unsigned longlong e;
char f;
}__attribute__((packed));
int main(int argc,char **argv){
printf("A = %d, B = %d, C = %d, D = %d, E = %d, F = %dn",
sizeof(struct A),sizeof(struct B),sizeof(struct C),sizeof(struct D),sizeof(struct E),sizeof(struct F));
return 0;
}
在一个 32位机 上运行结果如下:
[Copy to clipboard] [ - ]CODE:
[root@Kendo develop]# gcc -o align align.c
[root@Kendo develop]# ./align
A = 28, B = 32, C = 28, D = 28, E = 32, F = 20
[root@Kendo develop]#
我们看到
最后一个struct F,1 + 4 + 2 + 4 + 8 + 1 = 20,因为使用了__attribute__((packed));
来表示以最小方式对齐,所以结果刚好为20。
而第一个struct A,因为什么也没有跟,采用默认处理方式:4(1) + 4 + 4(2) + 4 + 8 + 4(1) = 28,括号中是其成员本来的大小。与此相似的是struct D。
接下来看struct E,采用8个字节的方式来对齐:8(1+4+2 ,即a, b, c)+ 8(4, d) + 8 + 8(1, f) = 32。
而在struct C中,试图使用__attribute__((aligned(1))) 来使用1个字节方式的对齐,不过并未如愿,仍然采用了默认4个字节的对齐方式。
在struct B中,aligned没有参数,表示“让编译器根据目标机制采用最大最有益的方式对齐"——当然,最有益应该是运行效率最高吧,呵呵。其结果是与struct E相同。
- __attribute__ ((aligned (n), packed))
- __attribute__ ((aligned (n), packed))
- __attribute__ ((aligned (n), packed))
- __attribute__ ((aligned (n), packed))
- __packed、#pragam pack()、 __attribute__(aligned(n))、 __attribute__(packed(n))字节对齐
- gcc __attribute__ ((packed)) || __attribute__ ((aligned(4))) 2
- __attribute__ ((packed))
- __attribute__ ((packed))
- __attribute__ ((packed))
- __attribute__((packed))
- __attribute__((packed))
- __attribute__((packed))
- __attribute__ ((packed))
- __attribute__ ((packed))
- __attribute__((packed))
- __attribute__((packed))
- #pragma pack(n)和__attribute__((aligned(m)))的区别:
- #pragma pack(n)和__attribute__((aligned(m)))的区别
- c#中连接数据库后绘制柱状图和饼状图
- Red Bend与阿朗推LTE移动设备管理 使4G设备兼容OMA DM
- Android学习备忘019——AlertDialog问题
- 字对齐概念
- 表达式求值[java版本]
- __attribute__ ((aligned (n), packed))
- loading图标现在相关链接
- printf修饰符
- [分享] 教你如何让谷歌浏览器新建标签自动打开你想要的网址
- C++ Map 容器
- Map使用之关联数组
- UBOOT详细解读
- 霍夫曼编码的另一种理解
- Android4.1.2原生输入法的bug