Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do these C struct definitions give warnings and errors?

Tags:

c

gcc

struct

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.

like image 564
gsingh2011 Avatar asked Jun 02 '13 03:06

gsingh2011


1 Answers

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 :)

like image 75
kfsone Avatar answered Nov 14 '22 21:11

kfsone