读取结构大小时遇到​​麻烦

KcF*_*nMi 5 c

如果我调试以下代码,那么我看到size值为12(如预期的那样).

#include <cstdint>

int main(int argc, char *argv[])
{
    typedef struct __attribute__((__packed__))  { int8_t value; } time;

    typedef struct __attribute__((__packed__))  {
        uint8_t msg[8];
//        time t1;
        uint32_t count;
    } theStruct;

    theStruct s;
    int size = sizeof(s);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有趣的是,在"时间t1;"删除评论,值为size16.我期待13.

我知道(或多或少)这是由数据结构填充故事解释的......

但是,有什么办法可以避免这个问题吗?怎么做才能阅读size = 13

eca*_*mur 4

MinGW 的MSVC 结构打包模拟存在一些问题。

解决方法是将-mno-ms-bitfields标志传递给编译器;这将导致它使用自己的布局算法,而不是尝试模拟 MSVC。

另请参阅结构打包和与 mingw 的对齐(ARM 但可能是相同的问题)。