0

I have a link error on the following code.

header file

    //we have a static class member std::map that I want to be read-only
    //the enums are numeric but not sequential
    typedef std::map<MyEnumType, std::string> MyStdMapType

    class MyClass { static const MyStdMapType myMap; }
    

source file

    //populate - static var outside of class
    const MyStdMapType MyClass::myMap = { {enumVal1, str1}, ... }
    

Then, later, I want to iterate through the map

      for (MyStdMapType::const_iterator iter = MyClass::myMap.begin(); iter != MyClass::myMap.end(); iter++)
      {
<stuff>
      }

The "for" line is giving a link error. If I comment the line out, it compiles!:

error LNK2001: unresolved external symbol "public: static class std::map<enum MyEnumType,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,struct std::less<enum MyEnumType>,class std::allocator<struct std::pair<enum MyEnumType const ,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > > > const MyClass::myMap" (?myMap@MyClass@@2V?$map@W4MyEnum@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@U?$less@W4MyEnum@@@3@V?$allocator@U?$pair@$$CBW4MyEnum@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@std@@@3@@std@@B)
7
  • Essentially, you need to include const MyStdMapType myMap; in a source file (not a header) somewhere. Commented Jul 1, 2020 at 21:20
  • Brethren: Points taken - agreed. My apologies. I've updated the post. To summarize: 1. typedef defined in header. Static class variable declared in class in header. 2. Relevant class variable defined and initialized in cpp file. I'm aware [through bitter experience!] of the intricacies of setting up static variables... Rgds Steve Commented Jul 2, 2020 at 0:50
  • How can this be a duplicate if he is assigning a value to the static variable in a source file? Commented Jul 2, 2020 at 1:02
  • More details: I have other static vars set up, and they work fine. If I move the iterative code into the same class, it compiles fine. The problem occurs when I'm accessing the [public static] variable from another class in another cpp, #including the relevant header. Rgds Steve Commented Jul 2, 2020 at 1:25
  • 1
    I have voted to reopen this as I don't think it is a duplicate. Commented Jul 2, 2020 at 4:05

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.