Weird linker error with static std::map

12,173

You've declared the static member _myMap, but not defined it. Add this line just above int main():

std::map<int, int> MyClass::_myMap;

Think of it like a function that has been declared but not defined in any .cpp file - you get a linker error if you use it.

Share:
12,173

Related videos on Youtube

BlaBla
Author by

BlaBla

Updated on August 28, 2020

Comments

  • BlaBla
    BlaBla almost 4 years

    Why do I get linker error when I try to compile this in Visual Studio 2008

    #include <stdafx.h>
    #include <iostream>
    #include <map>
    #include <string>
    
    class MyClass
    {
    public:
     MyClass () { };
     virtual ~MyClass() {};
    
     static std::string niceString (std::map<int, int> mappp) { _myMap = mappp; return "nice string"; };
    
    private:
     static std::map<int, int> getMap ( ) { return _myMap; };
    
     static std::map<int, int> _myMap;
    }; 
    
    int main(){
    
     std::map<int, int> mappp;
    
     mappp[1] = 1;
    
     std::cout << MyClass::niceString(mappp);
    
    }
    

    error is:

    Error 1 error LNK2001: unresolved external symbol "private: static class std::map<int,int,struct std::less<int>,class std::allocator<struct std::pair<int const ,int> > > MyClass::_myMap" (?_myMap@MyClass@@0V?$map@HHU?$less@H@std@@V?$allocator@U?$pair@$$CBHH@std@@@2@@std@@A) test22.obj test22
    
  • BlaBla
    BlaBla almost 14 years
    is this also needed if I have another static variable, e.g. std::string myString ?
  • sergiol
    sergiol almost 9 years
    I think you did not mean " but not defined it", but instead "but not initialized it"
  • VitorMM
    VitorMM over 4 years
    2019, and that mistake still don't prompt a more specific error message in Visual Studio...