Why don't symbols (functions and variables) that are defined in an anonymous namespace have internal linkage as with static keyword? If a function is not visible/accessible outside, what is the reason to have external linkage?
An anonymous namespace makes the enclosed variables, functions, classes, etc. available only inside that file. In your example it's a way to avoid global variables. There is no runtime or compile time performance difference.
Unnamed NamespacesAlso see Static Variables. All declarations can be given internal linkage by placing them in unnamed namespaces, and functions and variables can be given internal linkage by declaring them static . This means that anything you're declaring can not be accessed from another file.
In practice, this means that you must define an identifier in a place which is visible to all, such that it has only one visible definition. It is the default linkage for globally scoped variables and functions. Thus, all instances of a particular identifier with external linkage refer to the same identifier in the program.
Thus, the declaration of an externally linked identifier does not take up any space. Extern identifiers are generally stored in initialized/uninitialized or text segment of RAM. Please do go through Understanding extern keyword in C before proceeding to the following examples. It is possible to use an extern variable in a local scope.
Internal Linkage: An identifier implementing internal linkage is not accessible outside the translation unit it is declared in. Any identifier within the unit can access an identifier having internal linkage. It is implemented by the keyword static.
There are 2 types of linkage: Internal Linkage: An identifier implementing internal linkage is not accessible outside the translation unit it is declared in. External Linkage: An identifier implementing external linkage is visible to every translation unit.
In C++03, names with internal linkage were forbidden from being used as template arguments[*]. So, names of most things in unnamed namespaces had external linkage to allow their use with templates. You could explicitly give a name internal linkage in an unnamed namespace by declaring it static
, same as in a named or global namespace.
Both things changed in C++11 -- names in unnamed namespaces have internal linkage by default (3.5/4), and names with internal linkage can be used as template arguments.
[*] for types, it must have external linkage. For objects and functions, it must have external linkage if its address is used as a template argument, although it's OK for example to use as a template argument the value of a const integer with 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