c++11 - 使用 C++11 的 MinGW 和压缩结构对齐

标签 c++11 struct g++ mingw memory-alignment

对于下面的结构,结构的实际(没有填充)大小是 54。在装有 MinGW (GCC) 4.8.1 x86_64 的 64 位 (Windows 7) 机器上,我get sizeof(BMPHeader) 为56,可以理解。根据 BMP 文件格式的要求,结构应该没有填充。我有三个选项(优先排序):

  1. C++11 的 alignas(1)
  2. struct __attribute__ ((packed)) BMPHeader
  3. #pragma pack(1)

然而,最后一个选项(优先级最低)似乎单独工作给我 54。这是编译器中的错误还是我在这里完全弄错了什么?商会

#include <iostream>

struct alignas(1) BMPHeader
{
    // BMP header
    uint16_t magic;
    uint32_t fileSize;
    uint32_t reserved;
    uint32_t dataOffset;

    // DIB header
    uint32_t dibHeaderLength;
    uint32_t width;
    uint32_t height;
    uint16_t numColourPlanes;
    uint16_t bitsPerPixels;
    uint32_t biBitFields;
    uint32_t dataSize;
    uint32_t physicalWidth;
    uint32_t physicalHeight;
    uint32_t numPaletteColours;
    uint32_t numImportantColours;
};

int main()
{
    std::cout << sizeof(BMPHeader) << std::endl;
}

最佳答案

  1. alignas 不能像 Martinho 指出的那样在这种情况下使用,因为我们要求的对齐比结构的自然对齐更宽松。这在 dcl.align 下的标准中指定(强调了相关部分):

When multiple alignment-specifiers are specified for an entity, the alignment requirement shall be set to the strictest specified alignment.

The combined effect of all alignment-specifiers in a declaration shall not specify an alignment that is less strict than the alignment that would be required for the entity being declared if all alignment-specifiers were omitted (including those in other declarations).

alignof(BMPHeader) 返回的 BMPHeader 的对齐方式是 4,因此任何对齐方式都不那么严格(不那么宽)不荣幸。

  1. __attribute__ ((packed)) 在使用 GCC 作为 specified in its manual 时肯定是正确的方法使结构紧凑。但是,由于 bug in MinGW,这不起作用和 works fine使用 GCC 时。

  2. 因此目前在 MinGW 中唯一的方法是使用 #pragma pack(1) 凑合。参见 #pragma pack effect有关此方法的更多详细信息。

另见

关于c++11 - 使用 C++11 的 MinGW 和压缩结构对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20144145/

相关文章:

python - C++11 正则表达式混淆

c - 在文件范围内修改的变量 Struct C

c - 将指向结构的指针/引用传递给函数

c++ - 使用用户输入信息初始化结构

c++ - g++ 警告 "will be initialized after",无论实际顺序如何

c++ - 使用 pqxx 编译程序时出现问题

lua - xmake总是报: error: cannot get program for cxx, 为什么?

C++随机引擎不是真正随机的

c++ - 得到错误的输出

c++ - 即使 XZY 具有非复制约束,构造助手 make_XYZ 也允许 RVO 和类型推导