Linker problem

Hello,

I'm new to C++ and I'm having a small problem working with templates for a generic tree. For practice I'm making an Npuzzle solver. Since I already made it in Java, I figure I'll make it in C++.

The problem I'm getting is in npuzzle.cpp when I try to call the addChild() function. Any help on what I'm doing wrong would be appreciated. Thanks.

Here is the error I'm getting:

Building target: NPuzzle
Invoking: MacOS X C++ Linker
g++ -arch i386 -o "NPuzzle" ./src/Puzzle.o ./src/Tree.o ./src/astar.o ./src/manhattan.o ./src/npuzzle.o
Undefined symbols:
"Tree<Puzzle>::addChild(Puzzle)", referenced from:
_main in npuzzle.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make: *** [NPuzzle] Error 1


Here some code that's in Tree.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef TREE_H_
#define TREE_H_

template <class T>
class Tree
{
   public:
      void addChild (T nodeToAdd);
      void removeChild (T nodeToRemove);
};


#endif /* TREE_H_ */ 


Tree.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "Tree.h"

template <class T>
void Tree<T>::addChild(T nodeToAdd)
{
   // foo
}

template <class T>
void Tree<T>::removeChild(T nodeToRemove)
{
   // foo
}


npuzzle.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include "npuzzle.h"
#include "Tree.h"

using namespace std;

int main()
{
   int mixed[SIZE][SIZE] = {{0,4,5},{8,7,2},{3,1,6}};
   int goal[SIZE][SIZE] = {{1,2,3},{4,5,6},{7,8,0}};

   Puzzle start_state (mixed);
   Puzzle goal_state (goal);

   Tree <Puzzle> puzzle_tree;
   puzzle_tree.addChild(start_state);
}


You have found the bug with templates.

In order for templates to work properly you have to have the entire class defined in the same file. Templates will not work if you have a .h file and a .cpp file.
Ok, I combined Tree.h and Tree.cpp

and I get this:

npuzzle.cpp"
../src/npuzzle.cpp: In function 'int main()':
../src/npuzzle.cpp:21: error: 'Tree' was not declared in this scope
../src/npuzzle.cpp:21: error: expected primary-expression before '>' token
../src/npuzzle.cpp:21: error: 'puzzle_tree' was not declared in this scope
make: *** [src/npuzzle.o] Error 1


So how would I correctly tell npuzzle.cpp to look at Tree.cpp?
Last edited on
You have to put the entire definition of Tree in Tree.h, not Tree.cpp.
Ahh, awesome. Thank you for answering to my stupidity. Everything compiles smoothly now. :)
Topic archived. No new replies allowed.