Hi guys, I'm getting " SingletonMain.C:18: undefined reference to `Singleton<MyClass>::instance()' " compiling error.

It doesn't make sense to me because MyClass inherits instance() from Singleton, doesn't it ?

If someone could shed some light on it, I will be grateful.

SingletonMain.C

#include <iostream>
#include "Singleton.h"

using namespace std;

class MyClass : public Singleton<MyClass> {
  friend class Singleton<MyClass>;
  public:
    void setValue(int n) { x = n; }
    int getValue() const { return x; }
  protected:
    MyClass() { x = 0; }
  private:
    int x;
};

int main() {
   MyClass& m = MyClass::instance();
   cout << m.getValue() << endl;
   m.setValue(1);
   cout << m.getValue() << endl;
   MyClass& n = MyClass::instance();
   cout << n.getValue() << endl;
   n.setValue(10);
   cout << m.getValue() << endl;
   cout << n.getValue() << endl;
}

Singleton.h

#ifndef SINGLETON_H
#define SINGLETON_H

template<typename T>
class Singleton {
    Singleton(const Singleton&);
  protected:
    Singleton() {}
    virtual ~Singleton() {}
  public:
    static T& instance();
};

#endif // SINGLETON_H

Singleton.cpp

#include "Singleton.h"

template<typename T>
T& Singleton<T>::instance() {
  static T* theInstance = new T;
  return *theInstance;
}

Thanks!

Why are you using a .C file-extension for SingletonMain and why a .cpp file-extension for the file Singleton ???

I would just use .cpp for both file's extensions, as it's the most common :) ...

When I put #include "Singleton.cpp" in SingletonMain.cpp it compiles. This is confusing me . .

When I put #include "Singleton.cpp" in SingletonMain.cpp it compiles. This is confusing me . .

That's because the compiler is just replacing the #include directive with the whole contents of Singleton.cpp , so the compiler's pre-processor threats it as a header file :)

Your problem is with the way you're compiling your program.
In g++, compile your code as : g++ -o OUTPUT.EXE SingletonMain.C Singleton.cpp This is not an compiler error but a linker error. Your linker do not have access to Singleton.cpp hence he doesn't have definition of Singleton<T>::instance() hence the error.

This article has been dead for over six months. Start a new discussion instead.