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 foois not packed insidestruct bar, which has thepackedattribute; thestruct barobject created contains three bytes of padding (visible as.zero 3) inside itsstruct foomember, between thestruct foomemberscandi.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
packedto a structure is equivalent to applying it to its members, it meant the effect of applyingpackedto the “variable” that is the member, described in the documentation for variable attributes. Whenpackedis 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.)