Search code examples
c++global-variableslinkageunnamed-namespace

What effect does an unnamed namespace have on a global variable?


What is the difference between these two in a source file?

namespace { int var; }
// or
int var;

if both are put in the cpp file, is not correct that we put a variable in an unnamed 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 private because you never do an include to .cpp file?


Solution

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