I was reading online about namespaces, and read about unnamed namespaces. I read that unnamed namespaces are only accessible within the file they were created in. But when I tried it on my own, it didn't work like that. How is that possible?
Here is what I did:
file1:
#include <iostream>
using namespace std;
namespace space1 {
int a = 10;
void f() {
cout << "in space1 of code 1" << endl;
};
}
namespace {
int x = 20;
void f() {
cout << "in unnamed space" << endl;
}
}
file2: where I accessed the namespace from file1
#include <iostream>
#include "code1.cpp"
using namespace std;
int main() {
space1::f();
cout << space1::a;
cout << x << endl;
f();
return 0;
}
CodePudding user response:
Can we access the unnamed namespaces outside the file they were created?
Depends on which "file" you're referring to. If you refer to the header file, then yes you can access the unnamed namespace outside, since the unnamed namespace is available to the entire translation unit that includes the header.
If you refer to the entire translation unit then no, the unnamed namespace cannot be accessed from other translation units.
CodePudding user response:
You claim that an unnamed namespace is limited to the file that creates it. That is not true. It is limited to the translation unit that creates it.
During the preprocessor stage, your #include "code1.cpp"
statement in file2
brings all of the code of code1.cpp
into the code of file2
. Thus, when file2
is compiled, both codes are part of the same translation unit, which is why the unnamed namespace in code1.cpp
is accessible to file2
's code.