c++namespacesunnamed-namespace

Are unnamed namespaces legal?


namespace { int Foo (int a); }

Is this code snippet legal? If so, can I reference Foo in anywhere, or only in a certain domain?


Solution

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