0

I want to use templates to implement generic linked lists, where each node of the list contains an element of class T.

This is linked_list.h

#ifndef LIN_LIS
#define LIN_LIS

#include "node.h"

template <class T>
class LinkedList {

 public:
  //
  Node<T>* head;

  //
  LinkedList() : head( 0 ) {}

  //
  ~LinkedList();
};

#endif

This is linked_list.cpp

#include <iostream>
#include "linked_list.h"

using std::cout;
using std::endl;

template <class T>
LinkedList<T>::~LinkedList() {
  Node<T>* p = head;
  Node<T>* q;
  while( p != 0 ) {
    q = p;
    //
    p = p->next;
    //
    delete q;
  }
}

And this is the test file

#include <iostream>
#include <ctime>
#include "linked_list.h"

using std::cout;
using std::endl;

int main() {

  //
  LinkedList<int> l;

  return 0;

}

This is my makefile

test_linked_0: test_linked_0.o linked_list.o
    $(CC) -o test_linked_0 test_linked_0.o linked_list.o $(CFLAGS)

I get the following error:

g++ -o test_linked_0 test_linked_0.o linked_list.o -I.
Undefined symbols for architecture x86_64:
  "LinkedList<int>::~LinkedList()", referenced from:
      _main in test_linked_0.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
make: *** [test_linked_0] Error 1

Any help would be much appreciated.

usual me
  • 8,338
  • 10
  • 52
  • 95

1 Answers1

0

You can not place the definition of LinkedList<int>::~LinkedList() in the .cpp file without explicit instantiation. Move it to the .h file.

user2672165
  • 2,986
  • 19
  • 27