Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Singleton in Xcode

I'm trying to make a Singleton class in C++ with Xcode. It's a really basic class and I get a linker error that I don't understand. Can any1 help please?

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)
like image 742
NicolasK Avatar asked Dec 28 '22 07:12

NicolasK


1 Answers

You need to declare actual storage for Network::_instance somewhere. Likely the impl. file.

Try adding to your impl file:

Network *Network::_instance=0;
like image 60
Managu Avatar answered Jan 08 '23 12:01

Managu