alignas
cannot be used in this situation as Martinho notes, since we're asking for an alignment less stricter than the natural alignment of the struct. This is specified in the standard under dcl.align (emphasised the relevant part):
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).
The alignment of BMPHeader
as returned by alignof(BMPHeader)
is 4
and thus any alignment less stricter (less wider) than that wouldn't be honoured.
__attribute__ ((packed))
is certainly the right way when using GCC as specified in its manual to make a struct tightly packed. However, this doesn't work due to a bug in MinGW and works fine when using GCC.So currently the only way in MinGW is to make-do with
#pragma pack(1)
. See #pragma pack effect for more details on this method.