简体   繁体   中英

Why does packing not work across sibling unions or structs

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)); 
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM