Why does packing not work across sibling unions or structs

自闭症网瘾萝莉.ら 提交于 2019-12-23 03:03:44

问题


In the following example I expect the size of complex_t to be the same as uint16_t: 2 bytes, however it's 3 bytes.

Removing the second union ("proximity_unsafe") reduces the size to 2 bytes, but I can't figure out the model of the packing rules.

#include <stdint.h>
#include <stdio.h>

typedef union {
    uint16_t unsafe;
    struct {
        uint16_t backwardmotion_unsafe    : 1;
        uint16_t batteryvoltage_unsafe    : 1;
        union {
            uint16_t dropoff_unsafe       : 4;
            struct {
                uint16_t dropofffrontleft_unsafe  : 1;
                uint16_t dropofffrontright_unsafe : 1;
                uint16_t dropoffsideleft_unsafe   : 1;
                uint16_t dropoffsideright_unsafe  : 1;
            }__attribute__((__packed__));
        }__attribute__((__packed__));
        union {
            uint16_t proximity_unsafe     : 3;
            struct {
                uint16_t proximityfront_unsafe    : 1;
                uint16_t proximityleft_unsafe     : 1;
                uint16_t proximityright_unsafe    : 1;
            }__attribute__((__packed__));
        }__attribute__((__packed__));
    } __attribute__((__packed__));
} __attribute__((__packed__)) complex_t;

int main()
{
    printf("sizeof(complex_t): %i", sizeof(complex_t));
    printf("sizeof(uint16_t):  %i", sizeof(uint16_t)); 
}

回答1:


Because it is legal to take the address of any named struct member that is not a bitfield, such non-bitfield members are required to start at byte boundaries. While it is not possible to take the address of anonymous members, and it would thus theoretically be possible for a compiler to allow such objects to start at arbitrary bit boundaries, that would imply that the layout of a structure would vary based upon whether its members were named.



来源:https://stackoverflow.com/questions/39172529/why-does-packing-not-work-across-sibling-unions-or-structs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!