10

In C++, I know that if I declare a function with static, it names will only exist to the compilation unit where it is declared / defined:

static void MyFunction() {...}

Also, if I declare my function inside an anonymous namespace, its name will only exist in the local compilation unit:

namespace
{
    void MyFunction() {...}
}

Also, I can use static inside the anonymous namespace:

namespace
{
    static void MyFunction() {...}
}

Is there any difference between those definitions?

Thank you

bcsanches
  • 2,362
  • 21
  • 32

1 Answers1

13

Yes, there is a difference.

First, let's be precise, even to the point of being pedantic: the names exist everywhere. The distinction is:

  • If a symbol is declared static (at namespace scope), it has internal linkage, which means that the same name in a different translation unit refers to a different entity.

  • An unnamed namespace generates a namespace whose name is unique to the translation unit. The symbol still has external linkage (provided it is not static), but there's no way you can name it in another translation unit.

The main difference involves templates. At least until C++11 (and maybe still, I haven't checked), any entity used to instantiate a template must have external linkage. So you could not instantiate a template on something declared static, or which implicitly had internal linkage.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • 1
    Yes, C++11 erased the requirement about needing external linkage for templates. Which is helpful, since I think the type of a lambda expression has no linkage. – aschepler May 31 '13 at 19:50
  • @aschepler It's helpful even without lambda, but of course, lambda opens a whole new vista of possibilities. – James Kanze Jun 01 '13 at 14:43