Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

anonymous namespace

Tags:

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?

like image 233
Merni Avatar asked Jul 29 '10 14:07

Merni


People also ask

What are anonymous namespaces?

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.

What is the use of unnamed namespace?

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.

What is meant by namespace?

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.

Why is an unnamed namespace used instead of static?

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.


1 Answers

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.

like image 98
Didier Trosset Avatar answered Oct 26 '22 18:10

Didier Trosset