首页 > 代码库 > __attribute__((packed))的作用
__attribute__((packed))的作用
__attribute__((packed))的作用
在结构体变量的声明中,经常可以看到__attribute__((packed))修饰符。这是做什么用的呢?请看一下程序:
#define u8 unsigned char #define u16 unsigned short #define u32 unsigned int int main() { struct { u16 reg; u32 test2; u8 test1; u8 val[256]; } msg = { .reg = 0x8001, .test1 = 0xff, .test2 = 0x71727374, .val = {0x11, 0x12, 0x13, 0x14}, }; u8* ptr = (u8*) &msg; int i; for (i=0; i<0x10; i++) printf("%02x ", ptr[i]); return 0; }
01 80 00 00 74 73 72 71 ff 11 12 13 14 00 00 00
如果在msg前加上__attribute__((packed)) ,程序变为:
#define u8 unsigned char #define u16 unsigned short #define u32 unsigned int int main() { struct { u16 reg; u32 test2; u8 test1; u8 val[256]; } __attribute__((packed)) msg = { .reg = 0x8001, .test1 = 0xff, .test2 = 0x71727374, .val = {0x11, 0x12, 0x13, 0x14}, }; u8* ptr = (u8*) &msg; int i; for (i=0; i<0x10; i++) printf("%02x ", ptr[i]); return 0; }
01 80 74 73 72 71 ff 11 12 13 14 00 00 00 00 00
因此可以看到,packed属性修改了编译器对结构体成员的布局,尽可能压缩存储空间。默认情况下,gcc会为了效率考量,会让char或者short独占一个双字(4字节)。
gcc手册的说明:
packed
packed
attribute specifies that a variable or structure field should have the smallest possible alignment—one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned
attribute.Here is a structure in which the field x
is packed, so that it immediately follows a
:
struct foo { char a; int x[2] __attribute__ ((packed)); };
有时间也看看这个:
http://stackoverflow.com/questions/8568432/is-gccs-attribute-packed-pragma-pack-unsafe
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。