cgcccompiler-optimizationbit-fieldsanonymous-struct

merge bit fields across anonymous structs in C


I have the following code :

typedef unsigned short u16;

struct S {
    struct {
        u16 a: 9;
        u16 b: 1;
        u16 c: 1;
        u16 d: 1;
    } __attribute__((packed));

    u16 e: 4;

} __attribute__((packed));

when I check sizeof(S), it returns 3. is it possible to somehow instruct gcc to merge bitfields across anonymous structs so that sizeof(S) returns 2.


Solution

  • The result you are looking for can be obtained by making the structure union instead, with two bit-fields overlapping. The bits "used" by the first bitfield will be marked as "reserved" in the second one:

    union S {
        struct {
            u16 a: 9;
            u16 b: 1;
            u16 c: 1;
            u16 d: 1;
        } ;
        
        struct {
            u16 reserved: 12; // Number of bits used in the first struct
            u16 e: 4;
        };
    };
    

    Demo