Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any diference between defining static function inside anonymous namespace and outside?

Tags:

c++

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

like image 488
bcsanches Avatar asked May 31 '13 19:05

bcsanches


1 Answers

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.

like image 62
James Kanze Avatar answered Nov 11 '22 11:11

James Kanze