C ++ Singleton in Xcode

I am trying to create a Singleton class in C ++ with Xcode. This is really a base class, and I get a linker error that I don't understand. Can anyone help?

Here is the class header file:

#ifndef _NETWORK_H_ #define _NETWORK_H_ #include <iostream> #include <list> #include "Module.h" using namespace std; /* * Assume only one network can run at a time * in the program. So make the class a singleton. */ class Network { private: static Network* _instance; list<Module*> _network; public: static Network* instance(); }; #endif 

Here is the impl file:

 #include "Network.h" Network* Network::instance() { if (!_instance) _instance = new Network(); return _instance; } 

Here is the compiler error:

 Undefined symbols for architecture x86_64: "Network::_instance", referenced from: Network::instance() in Network.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) 
+4
source share
2 answers

You need to declare the actual storage for Network::_instance somewhere. Probably an implant. file.

Try adding impl to your file:

 Network *Network::_instance=0; 
+6
source

You need to define your instance in the implementation file:

 #include "Network.h" Network *Network::_instance; 

static Network *_instance; just says that there is a Network::_instance somewhere. You must provide a single definition somewhere so that it truly exists.

+4
source

Source: https://habr.com/ru/post/1392827/


All Articles