在结构体变量的声明中,经常可以看到__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; }
#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; }
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
__attribute__((packed))的作用,布布扣,bubuko.com
原文地址:http://blog.csdn.net/lmh12506/article/details/25641853