Packed bit fields in c structures - GCC

前端 未结 2 426
Happy的楠姐
Happy的楠姐 2021-02-04 02:47

I am working with structs in c on linux. I started using bit fields and the \"packed\" attribute and I came across a wierd behavior:

struct t1
{
    int a:12;
           


        
2条回答
  •  梦毁少年i
    2021-02-04 03:26

    struct t1 // 6 bytes
    {
        int a:12; // 0:11
        int b:32; // 12:43
        int c:4;  // 44:47
    }__attribute__((packed));
    
    struct t1 // 7 bytes
    {
        int a:12; // 0:11
        int b;    // 16:47
        int c:4;  // 48:51
    }__attribute__((packed));
    

    The regular int b must be aligned to a byte boundary. So there is padding before it. If you put c right next to a this padding will no longer be necessary. You should probably do this, as accessing non-byte-aligned integers like int b:32 is slow.

提交回复
热议问题