简体   繁体   中英

anonymous namespace

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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM