gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:23:37 27 4
gpt4 key购买 nike

对于下面的结构,结构的实际(没有填充)大小是 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com