Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ namespace.... anonymous namespace is legal?

Tags:

c++

namespaces

namespace { int Foo (int a) ; }

Like this. Is this code snippet legal?

Is this legal? and, can I reference Foo in anywhere? or only certain domain?

Thank you.

like image 482
Anders Lind Avatar asked Oct 06 '11 06:10

Anders Lind


People also ask

Can a namespace be unnamed?

Unnamed Namespaces The name of the namespace is uniquely generated by the compiler. The unnamed namespaces you have created will only be accessible within the file you created it in. Unnamed namespaces are the replacement for the static declaration of variables.

What is the point of anonymous namespace?

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. There is no runtime or compile time performance difference.

Can you use namespaces in C?

No, C does not have a namespace mechanism whereby you can provide “module-like data hiding”.

What is the purpose of namespace?

Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. All identifiers at namespace scope are visible to one another without qualification.


1 Answers

It is legal, You can use Foo anywhere in the same Translation Unit.

Anonymous namespace is the standard prescribed way of saying static on variables to limit their scope to the same Translation unit.

C++03 Standard section 7.3.1.1 Unnamed namespaces

para 2:

The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative.


Update:
As @Matthieu M. correctly points out in the comments, and his answer The C++11 Standard removed the above quote from C++03 Standard, which implies that the static keyword is not deprecated when declaring objects in a namespace scope, Anonymous or Unnamed namespaces are still valid nevertheless.

like image 65
Alok Save Avatar answered Sep 30 '22 01:09

Alok Save