Search code examples
c++classexternc++98

How to share a global class instance between files?


I have a class, myClass, which is split into a .h and .cpp file. I then have a main.cpp file, in which I declare a global instance of myClass as such

myClass class1(0,0);

I also have a few other cpp files which use class1, such as Funcs.cpp. Therefore, I created an extern file, extern.h, and declared the myClass instance as extern as well:

extern myClass class1;

There are two constructors available for myClass, one takes in two parameters and the other three (overloaded). There is no constructor which takes in no parameters. The constructor with two parameters is something like this:

myClass:myClass(int id, int mode);

My issue is that I am getting the following error message:

Identifier myClass is undefined "extern myClass class1"

...even though I have included myClass.h in both main.cpp, myClass.cpp and extern.h.

What is the correct way to share a global instance of myClass between several cpp files? I read through Issue declaring extern class object and the differences are that myClass has two parameters it takes in, and that my global instance is declared in main.cpp rather than myClass.cpp.


Solution

  • The problem could be the order of the include files. The compiler trustfully processes each compilation unit line by line, including the content of a .h file at the position of the #include.

    That means that you must include myclass.h before extern.h:

    #include "myclass.h"
    #include "extern.h"