__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/