码迷,mamicode.com
首页 > 其他好文 > 详细

__attribute__((packed))的作用

时间:2014-05-13 06:19:18      阅读:416      评论:0      收藏:0      [点我收藏+]

标签:style   class   code   c   tar   ext   

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

__attribute__((packed))的作用

标签:style   class   code   c   tar   ext   

原文地址:http://blog.csdn.net/lmh12506/article/details/25641853

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!