anonymous namespace

后端 未结 5 473
南旧
南旧 2020-12-25 14:03

What is the different between these two?

cpp-file:

namespace
{
    int var;
}

or

int var;

if both

相关标签:
5条回答
  • 2020-12-25 14:26

    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.

    0 讨论(0)
  • 2020-12-25 14:33

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

    0 讨论(0)
  • 2020-12-25 14:37

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

    0 讨论(0)
  • 2020-12-25 14:39

    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.

    0 讨论(0)
  • 2020-12-25 14:43

    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.

    0 讨论(0)
提交回复
热议问题