免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 96817 | 回复: 2
打印 上一主题 下一主题

关于linux内核中的"__attribute__ ((packed))" [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-08-23 10:57 |只看该作者 |倒序浏览

关于linux内核中的"__attribute__ ((packed))"  
来源:
http://jimmy-lee.blog.hexun.com/8001013_d.html
__attrubte__ ((packed)) 的作用就是告诉编译器取消结构在编译过程中的优化对齐,按照实际占用字节数进行对齐。
#define __u8    unsigned char
#define __u16   unsigned short
/* __attribute__ ((packed)) 的位置约束是放于声明的尾部“;”之前 */
struct str_struct{
        __u8    a;
        __u8    b;
        __u8    c;
        __u16   d;
} __attribute__ ((packed));
/*  当用到typedef时,要特别注意__attribute__ ((packed))放置的位置,相当于:
  *  typedef struct str_stuct str;
  *  而struct str_struct 就是上面的那个结构。
  */
typedef struct {
        __u8    a;
        __u8    b;
        __u8    c;
        __u16   d;
} __attribute__ ((packed)) str;
/* 在下面这个typedef结构中,__attribute__ ((packed))放在结构名str_temp之后,其作用是被忽略的,注意与结构str的区别。*/
typedef struct {
        __u8    a;
        __u8    b;
        __u8    c;
        __u16   d;
}str_temp __attribute__ ((packed));
typedef struct {
        __u8    a;
        __u8    b;
        __u8    c;
        __u16   d;
}str_nopacked;
int main(void)
{
        printf("sizeof str = %d\n", sizeof(str));
        printf("sizeof str_struct = %d\n", sizeof(struct str_struct));
        printf("sizeof str_temp = %d\n", sizeof(str_temp));
        printf("sizeof str_nopacked = %d\n", sizeof(str_nopacked));
        return 0;
}
编译运行:
[root@localhost root]# ./packedtest   
sizeof str = 5
sizeof str_struct = 5
sizeof str_temp = 6
sizeof str_nopacked = 6
--------------------------------------------------------------------
GNU C的一大特色就是__attribute__机制。__attribute__可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)。
__attribute__书写特征是:__attribute__前后都有两个下划线,并且后面会紧跟一对括弧,括弧里面是相应的__attribute__参数。
__attribute__语法格式为:
__attribute__ ((attribute-list))
其位置约束:放于声明的尾部“;”之前。
函数属性(Function Attribute):函数属性可以帮助开发者把一些特性添加到函数声明中,从而可以使编译器在错误检查方面的功能更强大。__attribute__机制也很容易同非GNU应用程序做到兼容之功效。
GNU CC需要使用 –Wall编译器来击活该功能,这是控制警告信息的一个很好的方式。
packed属性:使用该属性可以使得变量或者结构体成员使用最小的对齐方式,即对变量是一字节对齐,对域(field)是位对齐。


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/70379/showart_1145024.html

论坛徽章:
1
白羊座
日期:2014-01-14 17:31:01
2 [报告]
发表于 2011-01-13 15:39 |只看该作者
关于linux内核中的"__attribute__ ((packed))"  
来源:

__attrubte__ ((packed)) 的作用就是告诉编译器取 ...
mlch1816 发表于 2008-08-23 10:57



    后面括号内的参数,能否再进一步讲解一下呢
前面讲的很清楚了。

论坛徽章:
1
白羊座
日期:2014-01-14 17:31:01
3 [报告]
发表于 2011-01-13 15:39 |只看该作者
后面括号内的参数,能否再进一步讲解一下呢
前面讲的很清楚了。
gradkid 发表于 2011-01-13 15:39



    就是attribute-list,不同的时候分别表示什么意思,
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP