0
#ifndef CONFIG_CPP
#define CONFIG_CPP
#include <mutex>
using namespace std;
class Config {
 public:
  static Config* GetDefult(){
    if (p_instance == nullptr){
      mutex_.lock();
      if (p_instance == nullptr){
        p_instance = new Config();
      }
      mutex_.unlock();
    }
    return p_instance;
  }
 private:
  static Config* p_instance;
  static mutex mutex_;
  Config(){};
};
int main(){
  auto t1 = Config::GetDefult();
}
#endif //CONFIG_CPP

These messages appeared when I was running

/tmp/ccKc2m2t.o: In function Config::GetDefult()': Config.cpp:(.text._ZN6Config9GetDefultEv[_ZN6Config9GetDefultEv]+0xc): undefined reference to Config::p_instance' Config.cpp:(.text._ZN6Config9GetDefultEv[_ZN6Config9GetDefultEv]+0x16): undefined reference to Config::mutex_' Config.cpp:(.text._ZN6Config9GetDefultEv[_ZN6Config9GetDefultEv]+0x22): undefined reference to Config::p_instance' Config.cpp:(.text._ZN6Config9GetDefultEv[ZN6Config9GetDefultEv]+0x43): undefined reference to Config::p_instance' Config.cpp:(.text._ZN6Config9GetDefultEv[_ZN6Config9GetDefultEv]+0x48): undefined reference to Config::mutex' Config.cpp:(.text._ZN6Config9GetDefultEv[_ZN6Config9GetDefultEv]+0x54): undefined reference to `Config::p_instance' collect2: error: ld returned 1 exit status

q57259028
  • 59
  • 6

1 Answers1

0

Static data members have to be initialized outside the class declaration in a source file. They have a global scope and generally it is not a good idea to mix multi-threaded code with static.

class Config {
...
};

Config* Config::p_instance = nullptr;
TKA
  • 183
  • 2
  • 4