Since beginning of the times I've used to believe that __attrbute__((packed)) can be put on a struct or typedef, like that:
typedef struct __attribute__((packed)) {
uint8_t m1;
uint16_t m2;
uint8_t m3;
uint32_t m4;
uint8_t m5;
} junk;
But then someone pointed out that this obvious usage is not documented in the recent gcc manuals, for already several releases.
Rather it says (in v.12): "The [packed] attribute does not apply to non-member objects."
A whole struct is not a member object, correct?
So is the above example legal, or relies on UB (and can bite later)?
CodePudding user response:
The above example is legal. The documentation that you linked to is a listing of variable attributes, which are attached to individual variables, not whole structures. When the documentation says that the attribute "does not apply to non-member objects", it is saying that it does not apply to non-member variables. Nothing on that page applies to the usage of the packed
attribute shown here.
Instead, your example of using the packed
attribute is using a type attribute, which happens to have the same name as the packed
variable attribute; see here for the documentation. packed
is one of the attributes listed there; besides the name and somewhat related functionality (of controlling how fields are arranged in a structure), these two attributes are not related to each other.