Possible Duplicate:
Why can templates only be implemented in the header file?
I got the following error while compiling in g++ 4.5.5 on Linux while allegedly my code works fine on Windows.
A.o: In function `A::NewObj(int)':
A.cpp:(.text+0x39): undefined reference to `List<A>::Add(A*)'
collect2: ld returned 1 exit status
make: *** [program] Error 1
I have no idea what is wrong with my code. I’m not sure if I declared object list_A correctly.
The files:
A.h
#ifndef A_H
#define A_H
class A
{
public:
int key;
A() { key=0; }
A(int i) { key = i; }
void NewObj(int i);
};
#endif
A.cpp
#include "A.h"
#include "List.h"
static List<A> *list_A = new List<A>();
void A::NewObj(int i)
{
A *nobject = new A(i);
list_A->Add( nobject );
}
List.h
#ifndef LIST_H
#define LIST_H
template<typename Objct>
class Node
{
public:
Objct* datapiece;
Node *next, *previous;
Node() { next = previous = 0; }
Node ( Objct *object, Node *n = 0, Node *p = 0)
{
datapiece = object;
next = n; previous = p;
}
};
template<typename Objct>
class List
{
public:
List() { head = tail = 0; }
void Add( Objct* );
protected:
Node<Objct> *head, *tail;
};
#endif
List.cpp
#include "List.h"
#include <iostream>
template<typename Objct>
void List<Objct>::Add( Objct *o )
{
int i =5;
Node<Objct> *nnode = new Node<Objct>(o);
if ( o->key < i )
std::cout << "Ok" << std::endl;
}
main.cpp
#include <iostream>
#include "A.h"
#include "List.h"
int main()
{
A *magazyn = new A();
magazyn->NewObj(6);
}
makefile
CC=g++
CFLAGS=-c -Wall -pedantic
program: List.o A.o main.o
$(CC) List.o A.o main.o -o program
A.o: A.cpp List.h
$(CC) $(CFLAGS) A.cpp
List.o: List.cpp
$(CC) $(CFLAGS) List.cpp
main.o: main.cpp A.h
$(CC) $(CFLAGS) main.cpp
The problem is the fact that your template class
Listneeds to have its methods defined in every compilation unit that uses it. Templates usually don’t follow the one header, one implementation file rule. See this related question for more information: Why can templates only be implemented in the header file?