Unnamed namespaces (C++ only)
A namespace with no identifier before an opening brace
produces an unnamed namespace. Each translation unit may contain
its own unique unnamed namespace. The following example demonstrates
how unnamed namespaces are useful.
#include <iostream>
using namespace std;
namespace {
const int i = 4;
int variable;
}
int main()
{
cout << i << endl;
variable = 100;
return 0;
}
In the previous example, the unnamed namespace permits
access to i
and variable
without
using a scope resolution operator.The following example illustrates an improper use of unnamed
namespaces.
#include <iostream>
using namespace std;
namespace {
const int i = 4;
}
int i = 2;
int main()
{
cout << i << endl; // error
return 0;
}
Inside main
, i
causes
an error because the compiler cannot distinguish between the global
name and the unnamed namespace member with the same name. In order
for the previous example to work, the namespace must be uniquely identified
with an identifier and i
must specify the namespace
it is using.You can extend an unnamed namespace within the same translation
unit. For example:
#include <iostream>
using namespace std;
namespace {
int variable;
void funct (int);
}
namespace {
void funct (int i) { cout << i << endl; }
}
int main()
{
funct(variable);
return 0;
}
both the prototype and definition for funct
are
members of the same unnamed namespace.Note: Items defined in an unnamed namespace have internal
linkage. Rather than using the keyword
static
to
define items with internal linkage, define them in an unnamed namespace
instead.