使用#pragma pack(n)

  • 伪指令#pragma pack (n),编译器将按照n 个字节对齐
  • 伪指令#pragma pack (),取消自定义字节对齐方式
#pragma pack(1)
struct my_align_struct {
  uint32 u0:8;
  uint32 u1:8;
  uint32 u2:8;
  uint32 u3:16;
};
#pragma pack()
sizeof(my_align_struct) == 5 // 默认情况下gcc是按照四字节对齐的,sizeof(my_align_struct) == 8.

使用__attribute__属性

struct my_align_struct {
  uint32 u0:8;
  uint32 u1:8;
  uint32 u2:8;
  uint32 u3:16;
}__attribute__((packed, aligned(1)));
来自yaronspace.cn  本文链接:http://yaronspace.cn/blog/archives/1536