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?
An anonymous namespace makes the enclosed variables, functions, classes, etc. available only inside that file. In your example it's a way to avoid global variables.
Unnamed Namespaces They are directly usable in the same program and are used for declaring unique identifiers. In unnamed namespaces, name of the namespace in not mentioned in the declaration of namespace. The name of the namespace is uniquely generated by the compiler.
In computing, a namespace is a set of signs (names) that are used to identify and refer to objects of various kinds. A namespace ensures that all of a given set of objects have unique names so that they can be easily identified.
1.1 Unnamed namespaces, paragraph 2: The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative. Static only applies to names of objects, functions, and anonymous unions, not to type declarations.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With