I have some simple code for a template class.  If I define the class and 
implement it in one file, everything compiles fine.  If I put the class 
definition in a .h and the implementation in a .cpp file, I get errors.

For example, with the files

test1a.h:
#ifndef _TEST1A_
#define _TEST1A_
#include <iostream>
template <class T>
class X
{
public:
  X() {std::cout << "Constructor" << std::endl;}
  ~X() {std::cout << "Destructor" << std::endl;}
};
#endif

test1.cpp:
#include "test1a.h"
int main()
{
  X<int> Y;
}

I then compile as
g++ -c test1.cpp
g++ test1.o -o test1

Running the program produces
Constructor
Destructor
as expected.

Now, consider the following files.

test2a.h:
#ifndef _TEST2A_
#define _TEST2A_
template <class T>
class X
{
public:
  X();
  ~X();
};
#endif

test2a.cpp:
#include "test2a.h"
#include <iostream>
template <class T>
X<T>::X() {std::cout << "Constructor" << std::endl;}
template <class T>
X<T>::~X() {std::cout << "Destructor" << std::endl;}

test2.cpp:
#include "test2a.h"
int main()
{
  X<int> Y;
}

I try to compile as
g++ -c test2.cpp
g++ -c test2a.cpp
g++ test2.o test2a.o -o test2

and I get

test2.o(.text+0x24): In function `main':
: undefined reference to `X<int>::X()'
test2.o(.text+0x33): In function `main':
: undefined reference to `X<int>::~X()'
collect2: ld returned 1 exit status

Is this a bug, or am I missing something simple here?

Results of gcc -v
(cclnx01)[tmp](63)gcc -v
Reading specs from /usr/lib/gcc/i386-redhat-linux/3.4.3/specs
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --
infodir=/usr/share/info --enable-shared --enable-threads=posix --disable-
checking --with-system-zlib --enable-__cxa_atexit --disable-libunwind-
exceptions --enable-java-awt=gtk --host=i386-redhat-linux
Thread model: posix
gcc version 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)

Thanks,
Greg

-- 
           Summary: Problem with undefined references for templates
           Product: gcc
           Version: 3.4.3
            Status: UNCONFIRMED
          Severity: normal
          Priority: P2
         Component: c++
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: gregory dot a dot bakken at pfizer dot com
                CC: gcc-bugs at gcc dot gnu dot org


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23685

Reply via email to