What is the different between these two?
cpp-file:
namespace
{
int var;
}
or
int var;
if both
In your second case, when you don't use an anonymous namespace, if any other cpp file declares an extern int var;
, it will be able to use your variable.
If you use an anonymous namespace, then at link time, the other cpp file will generate an undefined reference error.
In addition to the reason given by Nikolai and others, if you don't use an anonymous namespace, you can get naming conflicts with other global data. If you do use an anonymous namespace, you will instead shadow the global data.
From cprogramming.com: "Within the namespace you are assured that no global names will conflict because each namespace's function names take precedence over outside function names."
The second version is defined in the global namespace -- other .cpp files can get to it by declaring
extern int var;
and even if they don't do that, if someone else uses the same name in the global name space, you'll get a link error (multiply defined symbol).
In the second case other .cpp
files can access the variable as:
extern int var;
var = 42;
and the linker will find it. In the first case the variable name is mangled beyond any reason :) so the above is not possible.
Two points:
extern int var;
can access your variable if it's not in an unnamed namespace.int var
global variable, you will have multiple definitions of this variable.As specified in the standard :
[...] all occurrences of unique in a translation unit are replaced by the same identifier and this identifier differs from all other identifiers in the entire program.