I am trying to initialise a static map of map<string, int>
in my program as follows:
testApp.h
class testApp(){
public:
void setup();
void update();
void renew();
static map<string, int> _someMap;
};
testApp.cpp
testApp::setup(){
_someMap["something"] = 1;
_someMap["something2"] = 2;
cout<<_someMap["something"]<<"\n";
}
I don't want to use boost
for this short use of map and add source dependency for my code. I am not on C++11
and I don't have the constructor here in the program since the class is some framework's class. I am on Xcode and on doing the above in .cpp
, I get the following error:
Undefined symbols for architecture i386:
"testApp::mapppp", referenced from:
testApp::setup() in testApp.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
-- >Additionally, let's say my map is private, for which I tried doing this in my class:
...
private:
static someVariable;
static void someFunction();
.cpp
testApp::setup(){
someFunction();
}
Error:
Undefined symbols for architecture i386:
"testApp::_someMap", referenced from:
testApp::someFunction() in testApp.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
C# language specification makes it pretty clear that static fields are initialized only once, before the class is first used: The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration.
The Static Initializer for a Static HashMap We can also initialize the map using the double-brace syntax: Map<String, String> doubleBraceMap = new HashMap<String, String>() {{ put("key1", "value1"); put("key2", "value2"); }};
In this article, a static map is created and initialized in Java. A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class.
You've declared the variable in the class definition, but it looks like you haven't defined it. Every static variable needs to be defined in exactly one translation unit. So add a definition to your source file:
map<string, int> testMap::_someMap;
If you like (and if you can't use a C++11 initialiser), you could avoid having to call the setup
function by initialising the map from the result of a function instead:
map<string, int> make_map() {
map<string, int> map;
map["something"] = 1;
map["something2"] = 2;
return map;
}
map<string, int> testMap::_someMap = make_map();
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