Click to See Complete Forum and Search --> : Linking Template


709394
09-06-2004, 08:51 PM
when I compile the program below, I got the following errors:

/tmp/cc8rlb0i.o(.text+0x18): In function `main':
: undefined reference to `A<int>::A[in-charge]()'
/tmp/cc8rlb0i.o(.text+0x27): In function `main':
: undefined reference to `A<int>::~A [in-charge]()'
collect2: ld returned 1 exit status

COMPILE CMD: g++ Main.cpp A.cpp -o a
Using g++ v3.3.1.
And if I put everything in 1 file, it compiles without any complaint.
Does someone knows what I did wrong?
thanx!



A.h

#ifndef _A_h
#define _A_h

template <class T>
class A
{
public:

/// Constructor
A();

/// Destructor
~A();


protected:


private:

};

#endif // _A_h


A.cpp

#include "A.h"

template <class T>
A<T>::A()
{
}

template <class T>
A<T>::~A()
{
}




Main.cpp

#include "A.h"

int main( void )
{
A<int> a;
return 0;
}

bwkaz
09-06-2004, 10:03 PM
You can't do what you're trying to do with templates -- templated classes don't act exactly like normal classes. With a templated class, you need the entire implementation of the class available to the compiler when it's compiling a program that uses the template. You'll see this if you look through the STL header files -- they declare their templated classes, and then implement all the class functions in the same header file, or in one included from it.

This is because the template is used more or less at compile time, not at runtime (so it's not like a normal function call, where the linker can resolve missing references after the compile -- it's much closer to a function prototype, which the compiler needs to know at compile time).

Just move the implementation into the A.h header file, and remove the A.cpp file from the compilation. Alternately, make all of these functions inline (that's what my STL <vector> header does).