C ++编译器正在更改我的结构的对齐方式.我该如何预防呢? [英] C++ The compiler is changing the alignment of my structures. How can I prevent this?
问题描述
我正在编写一些代码来读取位图文件.
I am writing some code to read bitmap files.
这是我用来读取位图标题的结构.另请参阅:
Here is the struct I am using to read the bitmap header. See also:
https://msdn.microsoft.com/zh-CN/library/windows/desktop/dd183374(v=vs.85).aspx
struct BITMAPFILEHEADER
{
WORD bfType; // 2
DWORD bfSize; // 6
WORD bfReserved1; // 8
WORD bfReserved2; // 10
DWORD bfOffBits; // 14
}; // should add to 14 bytes
如果在我的主要功能中输入以下代码:
If I put the following code in my main function:
std::cout << "BITMAPFILEHEADER: " << sizeof(BITMAPFILEHEADER) << std::endl;
程序打印:
BITMAPFILEHEADER: 16
似乎是在4字节边界上重新对齐结构中的数据,大概是为了提高效率.当然,这使我无法读取位图...即使是Microsoft和其他公司,也可以通过指定方式来做到这一点...
It appears to be re-aligning the data in the struct on 4-byte boundaries, presumably for efficiency. Of course this renders me unable to read a bitmap... Even though microsoft, and others, specifiy this is the way to do it...
如何防止结构重新对齐?
How can I prevent the structure re-alignment?
推荐答案
我发现的解决方案适用于Linux下的gcc编译器:
The solution I found which works on gcc compilers, under linux:
struct BITMAPFILEHEADER
{
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} __attribute__((packed));
也许有更好的,更交叉的编译器/平台方式,但是我不知道它是什么.
There is probably a better, more cross compiler/platform way of doing things, but I don't know what it is.
这篇关于C ++编译器正在更改我的结构的对齐方式.我该如何预防呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!