The current code above compiles and runs fine, with program output
123
However, as soon as I un-comment the single line of code in
1 2 3
int main(void){
//globalClass.changeInner(321);
}
it throws a compilation error:
1>main.cpp(26) : error C2065: 'globalClass' : undeclared identifier
1>main.cpp(26) : error C2228: left of '.changeInner' must have class/struct/union
1> type is ''unknown-type''
So, I thought the instance globalClass is a global variable of type testClass which was created via the anonymous namespace. How should I call it in main.cpp without moving the anonymous namespace code?
Also, could someone explain how the compiler treats globalSpace.cpp? None of the other 2 files mentions it; does the compiler automatically compile it anyway?
The whole point of putting something in an anonymous namespace means you only want it to be accessed in that source file. So if you have globalClass in an anon namespace in globalSpace.cpp... it can only be accessed from globalSpace.cpp. That's kind of the whole point.
It minimizes scope of global classes/variables/objects/functions. So if you make another global named globalClass in some other cpp file it won't conflict with this one.