__attribute__ ((packed)) 的作用

来源:互联网 发布:淘宝美工如何上新 编辑:程序博客网 时间:2024/05/16 05:31

看到内核代码里面有attribute ((packed)) ,感觉比较奇怪,查了百度后知道其作用。
attribute ((packed)) 的作用就是告诉编译器取消结构在编译过程中的优化对齐,按照实际占用字节数进行对齐,是GCC特有的语法。这个功能是跟操作系统没关系,跟编译器有关,gcc编译器不是紧凑模式的,在windows下,用vc的编译器也不是紧凑的,用tc的编译器就是紧凑的。例如:
在TC下:struct my{ char ch; int a;} sizeof(int)=2;sizeof(my)=3;(紧凑模式)
在GCC下:struct my{ char ch; int a;} sizeof(int)=4;sizeof(my)=8;(非紧凑模式)
在GCC下:struct my{ char ch; int a;}__attrubte__ ((packed)) sizeof(int)=4;sizeof(my)=5

在linux centos下运行:
gwwu@dev2.com:~/test/unix_enviroment>gcc -g attribute.c -o attribute -Wall
gwwu@dev2.com:~/test/unix_enviroment>./attribute
sizeof(event1) = 5, sizeof(event2)=8
gwwu@dev2.com:~/test/unix_enviroment>

gwwu@dev2.com:~/test/unix_enviroment>more attribute.c #include <stdio.h>#include <stdlib.h>struct event1{    char a;    int b;} __attribute__((packed));struct event2{    char a;    int b;};int main(){    printf("sizeof(event1) = %ld, sizeof(event2)=%ld\n", sizeof(struct event1), sizeof(struct event2));    return 0;}
原创粉丝点击