layout of __attribute__((packed)) vs. #pragma pack

Jim Wilson jim.wilson@linaro.org
Fri Aug 4 17:20:00 GMT 2017


On 07/28/2017 04:51 AM, Geza Herman wrote:
> There's an option in GCC "-mms-bitfields". The doc about it begins with:
> 
> "If packed is used on a structure, or if bit-fields are used, it may be 
> that the Microsoft ABI lays out the structure differently than the way 
> GCC normally does. Particularly when moving packed data between 
> functions compiled with GCC and the native Microsoft compiler (either 
> via function call or as data in a file), it may be necessary to access 
> either format."
> 
> I'm particularly interested in packed structs, bit-fields are not a 
> concern now. Does this doc mean, that a packed struct layout may differ 
> between GCC and MSVC? The doc doesn't give an example of this, it just 
> talks about bit-fields. If the packed layout can differ, in which way 
> does it? Previously I thought that both compilers put members into the 
> struct without any padding, so the layout must match.

Different ABIs handle bit-fields differently, and as a result, different 
ABIs handle packed structures with bit-fields differently.

There are testcases for this in the gcc testsuite.  In the gcc sources, 
look at gcc/testsuite/gcc.dg/bf-ms-layout.c.

Otherwise, for a packed structure without bit-fields, and without 
sub-structures, it is probably handled the same across most ABIs.

> Plus, __attribute__((packed)) documentation have changed:
> 
> https://gcc.gnu.org/onlinedocs/gcc-7.1.0/gcc/Common-Variable-Attributes.html, 
> here the text is:
> 
> The packed attribute specifies that a variable or structure field should 
> have the smallest possible alignment—one byte for a variable, and one 
> bit for a field, unless you specify a larger value with the aligned 
> attribute.
> 
> 
> https://gcc.gnu.org/onlinedocs/gcc/Common-Type-Attributes.html, here the 
> text is:
> 
> "This attribute, attached to struct or union type definition, specifies 
> that each member (other than zero-width bit-fields) of the structure or 
> union is placed to minimize the memory required"
> 
> 
> What does "minimize" mean here? Does it give the same guarantees as the 
> previous definition? Could it mean that there's still padding in the 
> struct?

Structure layout is complicated, and it isn't possible to explain all 
details in a single sentence.  There may be cases where a packed 
structure still contains padding.  It depends on the ABI, and how 
bit-fields are handled, etc.  You can see some examples with the 
-ms-bitfields examples given above, where some packed structures are 
larger with gcc than msvc, and some are larger with msvc than gcc.

If in doubt, the best solution is to write some testcases to check, or 
add some consistency checking code, e.g. you can add some code to verify 
that type sizes are what you expect at compile-time.

Jim



More information about the Gcc mailing list