Q:

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/en-us/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;

the program prints:
BITMAPFILEHEADER: 16

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?

A:

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.

