__attribute__ ((__packed__))

Redis-3.2.11源码 Redis在Src\Sds.h中构建了一种名为简单动态字符串(simple dynamic string, SDS)的抽象类型,其中定义结构体时用到了__attribute__ ((__packed__))。(其位置约束一般为放于声明的尾部“;”之前,为什么Redis源码中是放在struct之后?有知道的朋友还请指教。

struct __attribute__ ((__packed__)) sdshdr32 {
    uint32_t len; /* used */
    uint32_t alloc; /* excluding the header and null terminator */
    unsigned char flags; /* 3 lsb of type, 5 unused bits */
    char buf[];
};

GNU C的一大特色就是__attribute__机制。__attribute__可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)。

在使用__attribute__参数时,你也可以在参数的前后都加上(两个下划线),例如,使用__aligned__而不是aligned,这样,你就可以在相应的头文件里使用它而不用关心头文件里是否有重名的宏定义。

packed属性可以使得变量或者结构体成员使用最小的对齐方式,即对变量是一字节对齐,对域(field)是位对齐。,除非使用aligned属性指定较大的值 。

ubuntu14.04下测试
代码:
这里写图片描述
结果:
这里写图片描述

关于__attribute__参考资料:
该链接下的Function Attributes、Variable Attributes和Type Attributes

猜你喜欢

转载自blog.csdn.net/z_muyangren/article/details/78975756