Keil位字段分配了错误的union / struct大小

时间:2016-06-06 08:01:45

标签: sizeof unions bit-fields keil

Require all granted

汇编后typedef union { struct { union { struct { unsigned int dev_t : 4; // Device Type, see DEV_type_t unsigned int dev_n : 7; // Device Number }; unsigned int id : 11; // CAN_ID }; unsigned int online : 1; unsigned int reserved : 4; }; // 16 bit total uint16_t _raw; } CAN_prefix_t; 显示sizeof(CAN_prefix_t),但预计会3 bytes 2 bytes

有人可以建议如何以正确的方式定义上面的struct / union吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

这对我有用(对于我的项目来说,从设备和CAN总线的角度来看,最好有2个“视图”):

#pragma pack(push,1)

typedef union {
    struct {
        unsigned int dev_n      : 7;
        unsigned int dev_t      : 4;
        unsigned int online   : 1;
        unsigned int reserved : 4;      
    } dev;
    struct {
        unsigned int id              : 11;
        unsigned int online    :  1;
        unsigned int reserved  :  4;
    } can;
    uint16_t raw;
} CAN_prefix_t;

#pragma pack(pop)

重要信息:Keil编译器以相反的顺序分配位字段。

Keil也很难与嵌套工会合作。