0

I have two branches of in my LinkedList implementation. The Master is a simple one that caters only to integer data types. While the _templates one is designed with templates to provide service to any data type.

My master branch compiles perfectly with this:

g++ -0 t1 main.cpp LinkedList.cpp Node.cpp

On the flip side, when I try to compile my _templates branch with the same (I have the implementation changed in this branch with templates):

g++ -0 t1 main.cpp LinkedList.cpp Node.cpp

I get the Linking error:

undefined reference to `LinkedList<int>::LinkedList()'
undefined reference to `LinkedList<int>::~LinkedList()'

And just to be absolutely clear, my Constructor in _templates branch

template <class T>
LinkedList<T>::LinkedList() {

     head = 0;
     tail = 0;
}
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
user1343318
  • 2,093
  • 6
  • 32
  • 59

1 Answers1

1

When using templates, your entire implementation must be visible all files that implement it at all times. i.e. If you've got your class declaration inside a header, the definition must also be 'inside' that header (see below).

This is because the compiler cannot know what types may use it and thus can't reserve memory for the type (think about if it tried to make a LinkedList for every type ever; there isn't enough memory in the world to do that!). Because of this, a class of a particular type is only ever defined only ever occurs whenever you decide to instantiate it in your body of code. If you never use the class, it will only be plain text and the size of your program will be no larger.

There are some tricks to hiding your implementation inside the header, such as placing them in a file called "LinkedList.tem" or "LinkedList.tcc", etc. and then at the bottom of your header file putting: #include "LinkedList.tem". GCC uses the tcc extension from what I've seen.

cjdb01
  • 51
  • 3