Are unpacked struct in packed struct automatically packed by GCC?
In other words, do __packed__
attribute automatically propagates to nested structures?
That is to say:
struct unpackedStruct{
int16_t field1;
int32_t field2;
// etc...
}
struct packedStruct{
int16_t field1;
struct unpackedStruct struct1; // <-- Is this struct packed?
// etc...
} __attribute__((__packed__));
No, the inner structure is not packed. In this Godbolt example, we can see that struct foo
is not packed inside struct bar
, which has the packed
attribute; the struct bar
object created contains three bytes of padding (visible as .zero 3
) inside its struct foo
member, between the struct foo
members c
and i
.
Current documentation for GCC 10.2 explicitly says the internal layout of a member of a packed structure is not packed (because of the attribute on the outer structure; it could be packed due to its own definition, of course).
(In older documentation that said that applying packed
to a structure is equivalent to applying it to its members, it meant the effect of applying packed
to the “variable” that is the member, described in the documentation for variable attributes. When packed
is applied to a structure member, it causes the member’s alignment requirement to be one byte. That is, it eliminates padding between previous members and that member, because no padding is needed to make it aligned. It does not alter the representation of the member itself. If that member is an unpacked structure, it remains, internally, an unpacked structure.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With