471,078 Members | 830 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,078 software developers and data experts.

problem compiling singleton template class


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
1 2194

"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.

Similar topics

2 posts views Thread by Sean Dettrick | last post: by
7 posts views Thread by Tim Clacy | last post: by
3 posts views Thread by Alicia Roberts | last post: by
5 posts views Thread by Pelle Beckman | last post: by
13 posts views Thread by kamaraj80 | last post: by
3 posts views Thread by Raider | last post: by
5 posts views Thread by tobias.sturn | last post: by
15 posts views Thread by Nick Keighley | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.