打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
__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
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C语言 头文件
如何写出高效优美的单片机C语言代码
C语言之
细说结构字节对齐
【转】__attribute__((packed)) 指针传递,赋值错误问题。 - Linux/Unix社区 / 程序开发区
基于51单片机SHT11温湿度传感器检测程序(含电路图)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服