Undefined reference to template members
Asked Answered
T

1

3

I'm new to C++, and preparing a homework by using NetBeans IDE on Ubuntu 10.04. I use g++ as a C++ compiler.

The error message:

build/Debug/GNU-Linux-x86/Maze.o: In function `Maze':
Maze/Maze.cpp:14: undefined reference to `Stack<Coordinate>::Stack()'
Maze/Maze.cpp:14: undefined reference to `Stack<Coordinate>::Stack()'
Maze/Maze.cpp:69: undefined reference to `Stack<Coordinate>::push(Coordinate)'
Maze/Maze.cpp:79: undefined reference to `Stack<Coordinate>::isEmpty()'
Maze/Maze.cpp:87: undefined reference to `Stack<Coordinate>::destroy()'

And my related code:

Maze.h

#include "Coordinate.h"
#include "Stack.h"
....
....
/**
 * Contains the stack object
 *
 * @var  Stack stack
 * @access private
 */
Stack<Coordinate> *stack;
...
...

Maze.cpp

#include "Maze.h"
...
...
Maze::Maze()
{
    // IT SHOWS THAT THE FOLLOWING LINE HAS AN ERROR///
    stack = new Stack<Coordinate>;
    ///////////////////////////////////////////////////

    for( int y=0; y<8; y++ )
    {
        for( int x=0; x<8; x++ )
        {
            maze[y][x] = '0';
        }
    }
}
...
...

And according to the error output, Each line that I used stack variable has an error: Undefined reference.

Stack.cpp

#include "Stack.h"
...
...
template <class T> Stack<T>::Stack()
{
    // Create the stac!
    create();
}
...

I have googled it, but could not solve the problem. I think there is something wrong with my includes order, or maybe I used the pointers in a wrong way.

I also tried to create a makefile by myself, but the result did not change. I prepared this makefile according to this link: http://www.cs.umd.edu/class/spring2002/cmsc214/Tutorial/makefile.html

Here is my makefile:

maze: Maze.o Stack.o Coordinate.o
 g++ -Wall Maze.o Stack.o Coordinate.o -o maze

Maze.o: Maze.cpp Maze.h Stack.h Coordinate.h
 g++ -Wall -c Maze.cpp

Stack.o: Stack.cpp Stack.h
 g++ -Wall -c Stack.cpp

Coordinate.o: Coordinate.cpp Coordinate.h
 g++ -Wall -c Coordinate.cpp

Maze.h: Stack.h Coordinate.h

How could I overcome this error? Any ideas?

Thurible answered 4/11, 2010 at 20:14 Comment(2)
Show your Stack.cpp as well please.Rube
This question is similar to yours and it has more complete answers.Adlay
V
9

Stack is a template. The complete definition has to go in its header file. That is, do not separate it into a .h and a .cpp file.

Vociferous answered 4/11, 2010 at 20:21 Comment(1)
Thank you. This simple answer has just saved my life :)Thurible

© 2022 - 2024 — McMap. All rights reserved.