c++c++14mutexstatic-methodsunresolved-external

unresolved external symbol "private: static class variable" c++


I'm getting an error while creating a container in c++ with static method and locks.I'm not an expert in c++.Could anyone please help to find the real issue here? below is the code. I'm using v14

#include <iostream>
#include <map>
#include <string>
#include <mutex>
#include <shared_mutex>

class obj {};

class pricercache
{
    static  std::shared_mutex entry_mutex;
private:
    static std::map<std::string,obj>& getInstance()
    {
        static std::map<std::string, obj>    engines;
        return engines;
    }
public:

    pricercache(pricercache const&) = delete;
    void operator=(pricercache const&) = delete;

    static obj get(std::string const& key)
    {
        std::shared_lock<std::shared_mutex> lk(pricercache::entry_mutex);
        std::map<std::string, obj>::const_iterator const it =
            getInstance().find(key);        
        return it->second;
    }
    static void add(std::string const& key,
        obj engine)
    {
        std::lock_guard<std::shared_mutex> lk(pricercache::entry_mutex);
        auto& engines = getInstance();
        if (engines.find(key) == engines.end())
            engines.insert(std::make_pair(key, engine));
    }
};

int main()
{
    std::cout << "Hello World!\n";
    obj v1; 
    obj v2;
    pricercache::add("1", v1); 
    pricercache::add("2", v2);

    auto A = pricercache::get("1");
    auto b = pricercache::get("2");

    std::cout << "Done!\n";

    
}

The error I'm getting is :

error LNK2001: unresolved external symbol "private: static class std::shared_mutex pricercache::entry_mutex" (?entry_mutex@pricercache@@0Vshared_mutex@std@@A)

I would also welcome and really appreciate if you have any other suggestion about the container class. thanks in advance.


Solution

  • The compiler complains because you have declared the static member, but not defined. Somewhere in your code, you should define it like this

    std::shared_mutex pricercache::entry_mutex; // definition of the entry_mutex