Unnamed Namespaces

Hi, I have a question about global variables instantiated via unnamed spaces.

I implemented the following 3 files:

main.cpp
1
2
3
4
5
#include "testClass.h"

int main(void){
    //globalClass.changeInner(321);
}


globalSpace.cpp
1
2
#include "testClass.h"
namespace { testClass globalClass(123); }


testClass.h
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

class testClass {
public:
	inline testClass(int inner_) : inner(inner_) 
            { std::cout << inner << std::endl ;};
	inline void changeInner(int newInner_) 
            { inner = newInner_;  
              std::cout << inner << std::endl ; };
private:
	int inner;
};



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.
Topic archived. No new replies allowed.