Disable structure padding in C without using pragma

前端 未结 6 617
遥遥无期
遥遥无期 2021-01-11 16:33

How can I disable structure padding in C without using pragma?

6条回答
  •  一整个雨季
    2021-01-11 16:51

    If you really want structs without padding: Define replacement datatypes for short, int, long, etc., using structs or classes that are composed only of 8 bit bytes. Then compose your higher level structs using the replacement datatypes.

    C++'s operator overloading is very convenient, but you could achieve the same effect in C using structs instead of classes. The below cast and assignment implementations assume the CPU can handle misaligned 32bit integers, but other implementations could accommodate stricter CPUs.

    Here is sample code:

    #include 
    #include 
    
    class packable_int { public:
    
      int8_t b[4];
    
      operator int32_t () const       { return *(int32_t*) b; }
      void operator =  ( int32_t n )  { *(int32_t*) b = n; }
    
    };
    
    struct SA {
      int8_t   c;
      int32_t  n;
    } sa;
    
    struct SB {
      int8_t        c;
      packable_int  n;
    } sb;
    
    int main () {
      printf ( "sizeof sa  %d\n", sizeof sa );    // sizeof sa  8               
      printf ( "sizeof sb  %d\n", sizeof sb );    // sizeof sb  5               
      return 0;
    }
    

提交回复
热议问题