This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Template linking problem


I get the following error when I try to compile the following code.

Thank you for your help,

R.

harveybook:coding_tests hchapman$ g++ -Wall -o single single.cc
Undefined symbols:
  "Singleton<SingleClassBase>::ptr", referenced from:
      __ZN9SingletonI15SingleClassBaseE3ptrE$non_lazy_ptr in ccrQyAGD.o
ld: symbol(s) not found
collect2: ld returned 1 exit status


Interestingly enough, when I had all of the following code in two header files and a source file, the ptr=NULL in the Singleton constructor was enough to generate the linker error, but not when all code is placed in a single file. Then, I needed the single uncommented return(ptr) in Instance().



#include <stdio.h>


template<class Type>
class Singleton
{
public:
  static Type *Instance()
  {
    /*
    if (ptr == NULL)
    {
      ptr = new Type;
    }

    return(ptr);
    */
    return(ptr);
  }

  static void Destroy(void)
  {
    /*
    if (ptr != NULL)
    {
      delete ptr;
      ptr = NULL;
    }
    */
  }

private:
  Singleton()
  {
    ptr = NULL;
  }
  ~Singleton()
  {
    Destroy();
  }

  static Type *ptr;
};

class SingleClassBase
{
public:
  friend class Singleton<SingleClassBase>;

  int getA(void){ return(a); }
  void setA(int newA){ a = newA; }

protected:
  SingleClassBase(){ a = 7; }
  ~SingleClassBase(){}

  int a;
};

typedef class Singleton<SingleClassBase> SingleClass;

int main()
{
  printf("Get %d\n", SingleClass::Instance()->getA());
  SingleClass::Instance()->setA(99);
  printf("Get %d\n", SingleClass::Instance()->getA());
  SingleClass::Destroy();
  printf("Get %d\n", SingleClass::Instance()->getA());

  return(0);
}


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]