Unnamed/anonymous namespaces vs. static functions

Head Geek picture Head Geek · Sep 30, 2008 · Viewed 225.4k times · Source

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?

Answer

luke picture luke · Sep 30, 2008

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