Reputation: 163
Here is an example of two namespaces in two different files:
There is a namespace definition in file1.cpp where the main function is located like this. This namespace is defined outside of main(), so it is global.
namespace {
char const * const GID{ "SOMENAME" };
int summary( void );
}
Then in file2.cpp, the same GID is defined as:
namespace {
char const * const GID{ "SOMEOTHER_NAME" };
}
I think the GID constant char only sits in corresponding file. For example, SOMEOTHER_NAME is only used in file2.cpp. But if that's the purpose, isn't it better just use a different name than GID?
Also, if I want to use the summary() function in file1.cpp, then how to use the namespace in file1? Note that the namespaces don't have names.
Upvotes: 0
Views: 789
Reputation: 5730
Anonymous namespaces, such as you have declared, are inaccessible other than in the file they are declared or in files in which the declaration is included. In the file it is declared, the namespace is accessible without using a specific namespace. So in file1, summary()
is accessed as summary
. The GID declarations in file1 and file2 are in two different namespaces, so do not conflict with each other.
In effect, each anonymous namespace has a unique namespace name, but you are unable to access the name, which is why you cannot access an anonymous namespace from a file that does not contain or include that specific anonymous namespace.
Upvotes: 3