0

Since beginning of the times I've used to believe that __attribute__((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 does it rely on UB (that can bite later)?

0

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Is there any difference between __attribute__ ((__packed__)) and __attribute__ ((packed))?
@pmor No difference for gcc. TL;DR omitting underscores on attribute names is allowed. (For other compilers - not sure)
@ddbug Thanks. Another related example: to my knowledge GCC supports both __asm volatile and __asm__ __volatile__. I guess that they are functionally equivalent.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.