Why do these two struct definitions compile fine:
struct foo {
int a;
} __attribute__((packed));
typedef struct __attribute__((packed)) {
int a;
} bar;
While this one gives a warning:
typedef struct {
int a;
} baz __attribute__((packed));
warning: ‘packed’ attribute ignored [-Wattributes]
And this one gives an error and a warning:
typedef struct qux __attribute__((packed)) {
int a;
} qux;
error: expected identifier or ‘(’ before ‘{’ token
warning: data definition has no type or storage class [enabled by default]
As a novice C programmer, the fact that the last two definitions don't work seems like a fairly arbitrary choice on the parts of the language designers/compiler writers. Is there a reason for this? I'm using gcc 4.7.3.
typedef struct __attribute__((packed)) {
int a;
} bar;
vs
typedef struct {
int a;
} baz __attribute__((packed));
In the first you said "consider this anonymous structure, with the attribute packed, that has a member a. then create an alias for this structure, and name that 'bar'". The normal syntax for describing a struct without doing it anonymously and having to typedef it is
struct bar { int a; };
in the second declaration you said "consider this anonymous structure, that has a member a. then create an alias for this structure, and name that 'baz who is packed'".
It doesn't work because you're trying to apply the attribute to the alias in a typedef, not to the structure definition.
typedef <entity> <alias>;
I would advise putting on a hit on whomever suggested you use the "typedef" syntax for describing structs :)
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