How can we access an unnamed namespace outside the file it is created in?

  accessibility, c++, namespaces, scope

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;
}

Source: Windows Questions C++

LEAVE A COMMENT