Reputation: 774
I have a class in a header:
class Communicator {
public:
std::map<std::string,obj::obj_version<obj::tkt_metadata>*> local_objects;
}
When I compile I can create a Communicator later in the code and use the map as normal, with no problem.
However, as soon as I put after the class declaration:
extern Communicator comm;
And add:
Communicator comm;
To the implementation file for the header, I get "error: ‘obj’ was not declared in this scope" etc, where obj
is the namespace that contains obj_version and tkt_metadata (and precedes the inclusion of my communicator header).
What is going on here, and is there anything I can do to get it to compile correctly? Thanks!
Upvotes: 1
Views: 3098
Reputation: 774
Oh I've just discovered the problem via a helpful comment (it was deleted).
So one of my header files object.h
(that doesn't contain Communicator
but the objects that Communicator
works on) actually looks a bit like this:
-- obj_version and tkt_metadata
-- #include "communicator.h"
-- more stuff
My implementation file was like this:
-- #include "communicator.h"
-- define the functions
-- Communicator comm;
However, someone in a comment mentioned "Compilation Unit" in C++. Turns out headers aren't compiled by themselves, only implementation files are compiled and the headers are just put in place for each implementation file.
Therefore, whilst my Communicator
was included after my objects that it needed to see (in object.h), the implementation file was only including communicator.h, not object.h (which includes communicator.h in turn). The compilation unit tried to compile Communicator without having the objects in namespace obj defined before it.
So the answer is to put in communicator.cc:
-- #include "objects.h"
-- define the functions
-- Communicator comm;
It's rather a simple problem (and probably wouldn't have been answerable by anyone with only the information I gave) but thanks, you made me solve my own misunderstanding!
Upvotes: 1
Reputation: 1
Did you forget a ;
in your real code or just forgot to put it here??
class Communicator {
public:
std::map<std::string,obj::obj_version<obj::tkt_metadata>*> local_objects;
}; // <<<<< Note the ';' here!
Upvotes: 0