Still relatively new to C++
I have a header variable with a namespace with a few constants that looks something like this
namespace blah {
const std::string x="foo";
}
I have no problems accessing the variables this way - dosomething(blah::x); etc. Now I want to change the variable so it can be modified. If I just take out the const I get a linker error "duplicate symbol blah::x". Adding an extern here doesn't help:
namespace blah {
extern std::string x;
}
It says that extern is enabled by default and I get the same duplicate symbol error. Whats the right way to do this?
(EDIT in the latter case, I don't want to set the variable value yet. I want to derive it elsewhere and share the value. To clarify - I want to get rid of the const so I can change the value (e.g. using command line arguments. When I get rid of the const is when I get the errors about duplicate symbols.)
In the header file, you should declare the variable:
//blah.h
namespace blah {
extern std::string x; //declaration
}
And in the source file, you should define it as:
//blah.cpp
#include "blah.h"
namespace blah {
std::string x="foo"; //definition
}
Now include blah.h
in as many file as you want. You wouldn't see any redefinition error.
If you want to get rid of const
(as you said in the comment), then simply remove it, as I did.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With