Creating and Using Namespaces 653
18
LISTING18.9A An Unnamed Namespace
0: // file: one.cpp
1: namespace
2: {
3: int value ;
4: char p( char *p ) ;
5: //...
6: }
LISTING18.9B A Second Unnamed Namespace
0: // file: two.cpp
1: namespace
2: {
3: int value ;
4: char p( char *p ) ;
5: //...
6: }
7: int main( )
8: {
9: char c = p( char * ptr ) ;
10: }
In the case in which these two listings are compiled into the same executable,
each of the names,valueand functionp(), is distinct to its respective file. To
refer to a (unnamed namespace) name within a translation unit, use the name without
qualification. This usage is demonstrated in the previous example with the call to func-
tionp()within each file.
This use implies a usingdirective for objects referred to from an unnamed namespace.
Because of this, you cannot access members of an unnamed namespace in another trans-
lation unit.
The behavior of an unnamed namespace is the same as a staticobject having external
linkage. Consider this example:
static int value = 10 ;
Remember that this use of thestatickeyword is deprecated by the standards commit-
tee. Namespaces now exist to replace code as this static declaration. Another way to
think of unnamed namespaces is that they are global variables with internal linkage.
ANALYSIS