I've had trouble with setting up variables in namespaces multiple times already, but usually now solve it by having the setup be as follows:
.h
namespace MyNS {
extern Variable var;
}
.cpp
#include "MyNS.h"
Variable MyNS::var;
Now, this works fine with primitives, but becomes a problem when the Variable
object is somewhat of a more complex object.
Namely, my problem this time is that I would like to leave some variables uninitialized until I call a certain function. Something as follows:
.h
namespace MyNS {
extern Variable var;
void init();
}
.cpp
#include "MyNS.h"
Variable MyNS::var;
void MyNS::init() { var = Variable(a, b, c); }
This gives a compile time error, because Variable
does not have a default constructor (And I don't want it to have one). But when I remove the 2nd
line in the .cpp
, I get linker error unresolved external symbol
.
How can I solve this problem? How do I initialize a variable of a namespace "later"?
The "hacky" solution I have so far is to have my namespace hold a Variable*
, initialize it to nullptr
, and then assign it the actual object in my init
function. But that seems incredibly hacky for something so simple, since I have no actual reason for using pointers in this case.