Why does GCC pad this bit-field?

前端 未结 2 801
我寻月下人不归
我寻月下人不归 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:28

    While some older compilers used to regard int foo:3; as synonymous with e.g. long foo:3, or short foo:3, and simply place foo in whatever manner was convenient, the present C standard specifies that each bit field must fit entirely within a storage unit of the appropriate size. I have no idea what the rationale was for that specification, since the way bit fields are specified remains too vague to allow their use in portable code, but sometimes makes it impossible to pack things optimally. For example, the only way a 24-bit value could be stored efficiently within a structure would be to either have a machine which on a machine which supports 32-bit integers, or else have a 8 bits of data which could be placed adjacent to the 24-bit value (preceding or following) so as to "fill out" a 32-bit word.

    Fortunately, in your particular case, it's possible to avoid the inefficiency by rearranging your fields. It may also be possible to avoid the inefficiency by changing the declared type of each field to unsigned long long if your compiler supports bitfields using such a type [in that case, bit fields would be allowed to straddle 32-bit boundaries provided they didn't straddle a 64-bit boundary].

提交回复
热议问题