Issue
I'm curious about this fact as I came up with the following code:
namespace
{
int my_variable = 12;
void get_data_a_lot() {}
}
int main()
{
my_variable++;
get_data_a_lot();
}
and compiling with msvc I get the following:
00E 00000000 SECT4 notype External | ?my_variable@?A0x087c0a53@@3HA (int `anonymous namespace'::my_variable)
025 00000000 SECT6 notype () Static | ?get_data_a_lot@?A0x087c0a53@@YAXXZ (void __cdecl `anonymous namespace'::get_data_a_lot(void))
But when I compile with gcc I get the following:
002 00000000 SECT2 notype Static | _ZN12_GLOBAL__N_111my_variableE
003 00000000 SECT1 notype () Static | _ZN12_GLOBAL__N_114get_data_a_lotEv
So the question is: Is it correct behavior that "my_variable" is External or is it compiler bug?
Solution
The standard says
[basic.link]
4 An unnamed namespace or a namespace declared directly or indirectly within an unnamed namespace has internal linkage. All other namespaces have external linkage. A name having namespace scope that has not been given internal linkage above has the same linkage as the enclosing namespace if it is the name of
- a variable; or
- [...]
According to which my_variable
should have internal linkage. One must bear in mind however that how linkage is implemented is entirely up to the implementation. The fact MSVC doesn't tag the symbol Static
doesn't mean it's in violation of the standard. All the standard requires is an entity whose name has internal linkage is distinct from entities with the same name in other TU's, such that it can only be referred to by that name in the single TU it's defined in. The name mangling could very well be how MSVC easily accomplishes it.
Answered By - StoryTeller - Unslander Monica