tags:

views:

84

answers:

5

What is the different between these two?

cpp-file:

namespace
{
    int var;
}

or

int var;

if both are put in the cpp file? Is not correct that we put a variable in anonymous namespace so it can be private for just that file? But if we put a global variable in a cpp file is not that variable also privat because you never do an include to .cpp file?

+2  A: 

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).

Nathan Monteleone
+3  A: 

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.

Nikolai N Fetissov
+5  A: 

In your second case, when you don't use an anonymous namespace, if any other cpp files 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 wil generate an undefined reference error.

Didier Trosset
So I think you can get the same result by setting the variable as static.
Dacav
True. Also in C++ by defining it as const, which will imply static.
Didier Trosset
@Dacav: True. but the C++ way of doing it is to use an anonymous namespace. Using static is just a result of C++ being backward compatible with C.
Martin York
Static works, but is deprecated because it only applies to variables. Anonymous namespaces can contain other things, such as class definitions.
Jon Reid
@Jon Reid: good point. On the other side, however, if you declared a class into a `.cpp` file, then nobody will have it into its namespace as well. Conversely if you put the anonymous namespace into a `.h` you won't be able to manipulate anything inside it when you include the header file. Declaring a class won't add a symbol into your object file, while variables and function will do it.
Dacav
+2  A: 

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."

Justin Ardini
A: 

Two points:

  1. anyone using extern int var; can access your variable if it's not in an unnamed namespace.
  2. if in another file, you have another 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.

Scharron