__attribute__((packed))的作用
来源:互联网 发布:上海杰游网络 编辑:程序博客网 时间:2024/05/16 15:06
__attribute__((packed))的作用
在结构体变量的声明中,经常可以看到__attribute__((packed))修饰符。这是做什么用的呢?请看一下程序:
#define u8 unsigned char#define u16 unsigned short#define u32 unsigned intint 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 intint 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
0 0
- __attribute__ ((packed)) 的作用
- __attribute__ ((packed)) 的作用
- __attribute__ ((packed)) 的作用
- __attribute__ ((packed)) 的作用
- __attribute__ ((packed)) 的作用
- __attribute__ ((packed)) 的作用
- __attribute__((packed))的作用
- __attribute__ ((packed)) 的作用
- __attribute__ ((packed)) 的作用
- __attribute__ ((packed)) 的作用
- __attribute__ ((packed)) 的作用
- __attribute__ ((packed)) 的作用
- __attribute__ ((packed)) 的作用
- __attribute__((packed))的作用
- __attribute__((packed))的作用
- __attribute__ ((packed)) 的作用
- __attribute__((packed))的作用
- __attribute__ ((packed)) 的作用
- 惜
- bzoj4454: C Language Practice
- 数据结构--插入排序
- opengl纹理贴图是黑白的原因
- 跋涉不止(42)
- __attribute__((packed))的作用
- 设计模式:设计模式之概括
- 安卓自定义控件
- Binary XML file line #6: Error inflating class android.support.v4.view.ViewPager
- Python 爬虫学习2 向网页提交数据
- LeetCode - Delete Node in a Linked List
- 第一个程序(Java)_使用Notepad.exe和JDK
- 发布MFC ActiveX控件并实现自动更新
- C++匿名命名空间