Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to declare a variable using an anonymous struct

Tags:

c

gcc

The following code doesn't compile, I can understand why, but I need to make it work anyway, preferably in a standards compliant way.

extern const struct {  int x; } a;

const struct { int x; } a = {1};

The compiler says, "error: conflicting types for ‘a’", even though the types are identical, even though they are probably different anonymous instances.

So, how do I explain to the compiler that the two types are the same without giving the struct a name or using a typedef? Can it be done?

like image 718
Martin Avatar asked Jul 31 '26 16:07

Martin


1 Answers

The two struct declarations declare two distinct types.

The C standard is quite clear. §6.7.2.3/p5: "Each declaration of a structure, union, or enumerated type which does not include a tag declares a distinct type."

So in standard C, you're out of luck.

If you are prepared to use a gcc extension, the following should work:

extern const struct {  int x; } a;

__typeof(a) a = {1};

If you specify something like -std=gnu11, then you can even leave out the two underscores.

like image 59
rici Avatar answered Aug 04 '26 22:08

rici