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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With