__attribute_((packed))

__attribute__((packed))的作用是让编译器取消结构体在编译过程中的优化对齐,可以保证结构体在不同的处理器中有相同的大小。使用示例:

typedef struct __attribute__((packed)) {
    uint8_t protocolType[12];
    uint8_t packetType;
    uint8_t serviceType;
    uint8_t optRetCode;
    uint8_t reserved;
    uint32_t dataLen;
} PktHeader;

下面用一个例子进行解释:

typedef struct  {
   char aChar;
   int anInt ;
} s;

假如处理器是使用八个字节进行优化对齐。那么aChar将占据第1个字节,紧跟的7个字节将不被使用,然后anInt将从第9个字节开始。

假如处理器是使用四个字节进行优化对齐,那么aChar将占据第1个字节,紧跟的4个字节将不被使用,然后anInt将从第5个字节开始。

如果使用了__attribute__((packed))

typedef struct __attribute__((packed)) {
   char aChar;
   int anInt ;
} s;

那么将强制让anInt紧跟在aChar后边,aChar占据第1个字节,而anInt从第2个字节开始。


参考链接:http://www.linuxquestions.org/questions/programming-9/what's-this-__attribute__-packed-193570/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值