GCC基础

来源:互联网 发布:龙之信条身材捏脸数据 编辑:程序博客网 时间:2024/06/05 19:23

__attribute__((packed))解释


偶然机会发现在定义一个结构体时,在末尾加了一个__attribute__((packed)),网上查了一下它的用法,觉得可以记录下来。

首先,__attribute__这个关键字(前后各两个下划线),是GCC的特有语法,与操作系统无关,跟编译器有关,也就是代码在编译过程中,编译器根据这些关键字做相关的(优化)操作。具体语法是:__attribute__ ((attribute-list)),放在声明的尾部";"之前。

__attribute__可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute

packed是类型属性(Type Attribute)的一个参数,使用packed可以减小对象占用的空间。比如:

在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

内存对齐,往往是由编译器来做的,如果你使用的是gcc,可以在定义变量时,添加__attribute__,来决定是否使用内存对齐,或是内存对齐到几个字节,以上面的结构体为例:

//4字节对齐:
struct student
{
    char name[7];
    uint32_t id;
    char subject[5];
} __attribute__ ((aligned(4))); 


//不对齐:
struct student
{
    char name[7];
    uint32_t id;
    char subject[5];
} __attribute__ ((packed));




原创粉丝点击