J
Jim Strathmeyer
So I'm trying to implement a singleton template class, but I'm getting a
confusing 'undefined reference' when it tries to link. Here's the code
and g++'s output. Any help?
// singleton.h
template <class T>
class Singleton : public T {
public:
static T * Instance();
protected:
Singleton();
~Singleton();
private:
static Singleton<T> * instance;
};
// singleton.cpp
#include <iostream>
#include "singleton.h"
template <class T> Singleton<T> * Singleton<T>::instance = 0;
template <class T> T * Singleton<T>::Instance() {
return (instance?instanceinstance = new Singleton<T>));
}
template <class T> Singleton<T>::Singleton() {
std::cout << "constructing singleton" << std::endl;
}
template <class T> Singleton<T>::~Singleton() {
std::cout << "destructing singleton" << std::endl;
}
// a.h
class A {
protected:
A();
virtual ~A();
};
// a.cpp
#include "a.h"
#include <iostream>
A::A() {
std::cout << "constructing A" << std::endl;
}
A::~A() {
std::cout << "destructing A" << std::endl;
}
// main.cpp
#include "a.h"
#include "singleton.h"
#include <iostream>
int main(int argc, char ** argv) {
A * a = Singleton<A>::Instance();
return 0;
}
g++ -g -Wall -MD a.o main.o singleton.o -o a.out
main.o(.text+0x1f): In function `main':
main.cpp:8: undefined reference to `Singleton<A>::Instance()'
collect2: ld returned 1 exit status
make: *** [singleton] Error 1
confusing 'undefined reference' when it tries to link. Here's the code
and g++'s output. Any help?
// singleton.h
template <class T>
class Singleton : public T {
public:
static T * Instance();
protected:
Singleton();
~Singleton();
private:
static Singleton<T> * instance;
};
// singleton.cpp
#include <iostream>
#include "singleton.h"
template <class T> Singleton<T> * Singleton<T>::instance = 0;
template <class T> T * Singleton<T>::Instance() {
return (instance?instanceinstance = new Singleton<T>));
}
template <class T> Singleton<T>::Singleton() {
std::cout << "constructing singleton" << std::endl;
}
template <class T> Singleton<T>::~Singleton() {
std::cout << "destructing singleton" << std::endl;
}
// a.h
class A {
protected:
A();
virtual ~A();
};
// a.cpp
#include "a.h"
#include <iostream>
A::A() {
std::cout << "constructing A" << std::endl;
}
A::~A() {
std::cout << "destructing A" << std::endl;
}
// main.cpp
#include "a.h"
#include "singleton.h"
#include <iostream>
int main(int argc, char ** argv) {
A * a = Singleton<A>::Instance();
return 0;
}
g++ -g -Wall -MD a.o main.o singleton.o -o a.out
main.o(.text+0x1f): In function `main':
main.cpp:8: undefined reference to `Singleton<A>::Instance()'
collect2: ld returned 1 exit status
make: *** [singleton] Error 1