Unnamed/anonymous namespaces vs. static functions


A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so:

namespace {
    int cannotAccessOutsideThisFile() { ... }
} // namespace

You would think that such a feature would be useless -- since you can't specify the name of the namespace, it's impossible to access anything within it from outside. But these unnamed namespaces are accessible within the file they're created in, as if you had an implicit using-clause to them.

My question is, why or when would this be preferable to using static functions? Or are they essentially two ways of doing the exact same thing?

12/6/2017 6:57:51 PM

Accepted Answer

The C++ Standard reads in section 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.


The decision to deprecate this use of the static keyword (affect visibility of a variable declaration in a translation unit) has been reversed (ref). In this case using a static or an unnamed namespace are back to being essentially two ways of doing the exact same thing. For more discussion please see this SO question.

Unnamed namespaces still have the advantage of allowing you to define translation-unit-local types. Please see this SO question for more details.

Credit goes to Mike Percy for bringing this to my attention.

5/23/2017 12:17:55 PM

Putting methods in an anonymous namespace prevents you from accidentally violating the One Definition Rule, allowing you to never worry about naming your helper methods the same as some other method you may link in.

And, as pointed out by luke, anonymous namespaces are preferred by the standard over static members.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow