Extra bytes when declaring a member of a struct as uint32_t

后端 未结 4 1844
没有蜡笔的小新
没有蜡笔的小新 2021-01-21 10:32

I have a problem when using the uint32_t type from the stdint.h library. If I run the following code (on Ubuntu linux 11.10 x86_64, g++ version 4.6.1):

#include          


        
4条回答
  •  天涯浪人
    2021-01-21 11:03

    You need to declare to the compiler to pack the structure

    I believe that this will work for GCC

    struct test
        {
                unsigned char  field1;
                unsigned short field2;
                unsigned long  field3;
        } __attribute__((__packed__));
    

    In MS it would be something using the pragma packed

    http://www.cplusplus.com/forum/general/14659/

    #pragma pack(push, 1) // exact fit - no padding
    struct MyStruct
    {
      char b; 
      int a; 
      int array[2];
    };
    #pragma pack(pop) //back to whatever the previous packing mode was 
    

提交回复
热议问题