__attribute__((packed))的作用

本文详细解释了C++中__attribute__((packed))在结构体声明中的用途,通过对比使用和不使用该属性的情况,展示了其如何优化内存布局,减少不必要的空间浪费。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://blog.youkuaiyun.com/lmh12506/article/details/25641853

__attribute__((packed))的作用  

在结构体变量的声明中,经常可以看到__attribute__((packed))修饰符。这是做什么用的呢?请看一下程序:
[cpp] view plaincopyprint?
#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)) ,程序变为:
[cpp] view plaincopyprint?
#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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值