Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Warning: anonymous type with no linkage used to declare variable

I see this warning message when compiling (gcc 4.6.3, ubuntu) the example:

struct {
} a;

int main() 
{
}


warning: anonymous type with no linkage used to declare variable ‘<anonymous struct> a’ with linkage [enabled by default].

GCC does not give this warning. Only G++ does.

Adding static clears the warning:

static struct {
} a;

I couldn't figure out what it means, expecially why typeis related to linkage. I thought linkage depends on where and how a variable is declared, but not on the type of the variable itself.

like image 980
ROTOGG Avatar asked Jul 29 '13 00:07

ROTOGG


2 Answers

What this means is that the variable a has linkage, for example can be visible in other translation units. However its anonymous type has internal linkage only (no [external] linkage) so you can't actually access the variable a in any other translation unit since you can't access its type.

Making the variable static would give it internal linkage and so neither the type nor the variable would be visible in other translation units.

I'm not sure offhand (no access to compiler to check) if an anonymous namespace would serve the same purpose in this scenario.

like image 133
Mark B Avatar answered Oct 24 '22 03:10

Mark B


The error is because you declare a variable a which is has an anonymous type (no typename after struct). I'm assuming the warning is because you cannot declare a variable of that type again (without using decltype). I assuming g++ gives the warning and not gcc because c++ tends to be a stricter language. I also tested it with clang++ and clang and they do not produce any warnings even with -Wall.

I would assume static gets rid of the warning because it can only be used in that one file (meaning no external linkage), it would be difficult to use a in a different file because you wouldn't know it's type or have access to it's members.

EDIT: Unfortunately according to the link in the warning is indeed a bug (however minor) and has been fixed.

like image 8
aaronman Avatar answered Oct 24 '22 05:10

aaronman