Struct packing and alignment with mingw

我的未来我决定 提交于 2019-12-05 10:41:23

I fixed it by myself -> Compiling with -mno-ms-bitfields helps! The code above is indeed correct. It is necessary to tell mingw to use gcc's bitfield organisation instead of the microsoft style. Though the code can be uncompileable with microsoft compilers then, I do not care at this point.

According to the GCC manual's examples, the attribute should go after the struct's fields, i.e.:

// PC Code
typedef struct
{
    uint8_t var1;
    uint16_t var2;
} __attribute__((packed, aligned(1))) FILE;

I also dropped the pointless struct tag (_file).

The above has a sizeof value of 3 when I tested it quickly.

attribute packed is broken on mingw32 compilers. Another option is to use pragma pack:

#pragma pack(1)
typedef struct _file
{
  uint8_t var1;
  uint16_t var2;
} FILE;

Why don't place struct elements in descending size order instead? You wouldn't need to worry about the padding byte.

// ARM Code
typedef struct _file
{
    uint16_t var2;
    uint8_t var1;
} FILE;

typedef struct _file
{
    uint16_t var2;
    uint8_t var1;
} FILE;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!