I have 3 files in a linux static lib project where I’m having a link problem with a static field that I want to use in two class method implementation files. I have class1.h, class1main.cpp and class1utils.cpp. class1.h defines a class called class1 and has all static methods and a static field in it called pDb. The .cpp files define the implementation of the class1 methods split into two files.
In class1.h, I declare the static:
class class1 {
public:
static Database * pDb;
...
}
In class1main.cpp I define the actual static at the top:
Database * class1::pDb;
So, I thought I could just do the following in class1utils.cpp:
extern Database * class1::pDb;
But when I make the project and bring in the lib, pDb is multiply defined at link time. Can someone tell me how I can get reference the static in the second source file so I can use it (and it will link)?
If I move the methods in class1utils.cpp back into class1main.cpp, and get rid of class1utils.cpp the link works.
Thanks for any advice.
Corey.
You should simply include class1.h. Nothing else is necessary to declare the variable.
One reason for this is that if you could declare a static member variable without the class definition being present then the access specifier for the static member would be hidden. The compiler would be unable to check access permissions.
Besides, you can’t even refer to a member of class1 (as in
extern Database *class1::pDb;) without class1 having already been defined. If you tryclass class1; Database *class1::pDb;you should get an error that you’re using an undefined typeclass1. So the extern declaration is redundant.On another note, if you have a class with no non-static members that’s an indication you probably shouldn’t be using a class. C++ isn’t like Java where everything has to be in a class. In C++ you can simply declare free functions and variables, in a namespace if you want.
In this case, then you’d use extern to declare the variable in class1.h instead of using static: