Is there a difference between defining a static function inside an anonymous namespace and outside?

In C ++, I know that if I declare a function with static, its names will exist only in 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 compiler:

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

Alternatively, I can use static inside an anonymous namespace:

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

Is there a difference between these definitions?

thanks

+8
c ++
source share
1 answer

Yes, there is a difference.

Firstly, even more accurately, even to the pedantic: names exist everywhere. The difference is as follows:

  • If a character is declared static (in the namespace area), it has an internal relationship, which means that the same name in another translation unit refers to another object.

  • An unnamed namespace generates a namespace whose name is unique to the translation unit. A symbol still has an external character (unless it is static), but you cannot name it in another translation unit.

The main difference is the patterns. At least until C ++ 11 (and, perhaps, I haven’t tested it yet), any object used for an instance of the template must have an external connection. That way, you could not create a template for something declared static or that implicitly had an internal relationship.

+12
source share

All Articles