Why does GCC pad this bit-field?

前端 未结 2 796
我寻月下人不归
我寻月下人不归 2020-12-19 13:56

Program is in C using std=c99, this is on a 64-bit machine.

struct epochs {
    volatile unsigned int epoch    : 1;
    volatile unsigned int pulse    : 1;
          


        
2条回答
  •  独厮守ぢ
    2020-12-19 14:35

    volatile unsigned int epoch    : 1;
    volatile unsigned int pulse    : 1;
    volatile unsigned int active0  : 7;
    volatile unsigned int active1  : 7;
    

    ^ 32-bit (4 bytes)

    volatile unsigned int counter0 : 24; 
    

    ^ 32-bit (4 bytes)

    volatile unsigned int counter1 : 24; 
    

    ^ 32-bit (4 bytes)

    So 4 bytes more.

    C says :

    (C99, 6.7.2.1p10) "If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit"

    There is not enough space to put 24-bit (counter0) more in a 32-bit unit (likely the size of unsigned int in your system) that already holds 16-bit (epoch, pulse, active0, active1).

    You can use uin64_t instead of using unsigned int to pack your bit-fields in a 64-bit unit but it is implementation-defined whether your system supports it or not.

    (C99, 6.7.2.1p4) "A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type."

提交回复
热议问题