By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,002 Members | 1,286 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,002 IT Pros & Developers. It's quick & easy.

problem compiling singleton template class

P: n/a

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?instance:(instance = 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
Jul 22 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a

"Jim Strathmeyer" <st*********@nc.invalid> wrote in message
news:MY*******************@twister.southeast.rr.co m...

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?


Congratulations on asking the most frequently asked question on this group.

See the FAQ
http://www.parashift.com/c++-faq-lit...templates.html question
34.12 onwards.

john
Jul 22 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.