What is the difference in using unnamed namespace and global declaration?
Is there any specific context for using these two?
Can we access unnamed namespace components in external source files?
Unnamed namespace Vs Global declaration
4.3k views Asked by Kaushik At
2
The point of an unnamed namespace is to provide a unique namespace within a translation unit (= a source file) without requiring an explicit prefix. This allows you to guarantee that your global names won't clash with other, equal global names in other translation units.
For example:
You can link those two translation units together and know for certain that the two names
foo
will refer to the function defined in the respective file, and you do not violate the one-definition rule.Technically, you can think of an unnamed namespace as something like this:
Without this tool, the only way you could guarantee a non-violation of ODR would be to use
static
declarations. However, there's a subtle difference, in thatstatic
affects linkage, while namespaces do not.