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

ROTOGG picture ROTOGG · Jul 29, 2013 · Viewed 10.9k times · Source

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.

Answer

Mark B picture Mark B · Jul 29, 2013

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.