• gcc优化内存之 __attribute__((packed))


    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    typedef __u32 u32;
    typedef __s32 s32;
    typedef __u16 u16;
    typedef __s16 s16;
    typedef __u8  u8;
    typedef __s8  s8;
    struct tlv_header{
            u8 type;
            u16 length;
    }__attribute__((packed));
    
    struct eph_device_info
    {
        struct tlv_header device_header;
        u8 product_id;
        u8 variant_id;
        u8 application_version_major;
        u16 application_version_minor;
        u16 bootloader_version;
        u8 protocol_version;
        u8 crc;
    };
    
    void main()
    {
            printf("%d \n",sizeof(struct eph_device_info));
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    打印结果:

    12
    
    • 1
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    typedef __u32 u32;
    typedef __s32 s32;
    typedef __u16 u16;
    typedef __s16 s16;
    typedef __u8  u8;
    typedef __s8  s8;
    struct tlv_header{
            u8 type;
            u16 length;
    };
    //__attribute__((packed));
    struct eph_device_info
    {
        struct tlv_header device_header;
        u8 product_id;
        u8 variant_id;
        u8 application_version_major;
        u16 application_version_minor;
        u16 bootloader_version;
        u8 protocol_version;
        u8 crc;
    };
    
    void main()
    {
            printf("%d \n",sizeof(struct eph_device_info));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    打印结果:

    14
    
    • 1

    原因:
    attribute((packed)) 是gcc的优化选项,选择紧凑内存模式,结构体会不采用对齐的方式来使用内存,所以tlv_header加此编译选项时会只使用3字节内存,而不加此编译选项的话,会使用4字节内存(linux默认对齐系数为4,所有结构体需要是对齐系数的整数倍)。

    修改对齐系数:
    #pragma pack(8)貌似在gcc下不能生效,一些人的解释是,如果linux默认是4那么,如果设置大于4的对齐方式都是不能生效的。

    目前我的平台默认应该是2,修改为#pragma pack(1)则可实现1字节对齐

  • 相关阅读:
    BSP Day56
    python之kafak应用demo
    深入浅出继承
    Java代码中如何向HashMap对象中添加(Map集合对象)呢?
    GPT-人工智能如何改变我们的编码方式
    C#实现的曲线方法
    关于python中的装饰器(Decorator)的讲解
    神器 CodeWhisperer
    LLMOps快速入门,轻松开发部署大语言模型
    使用Reflect封装Excel导出工具类
  • 原文地址:https://blog.csdn.net/u012441962/article/details/127984295