【问题标题】:Undefined reference to template members对模板成员的未定义引用
【发布时间】:2011-05-05 07:02:42
【问题描述】:

我是 C++ 新手,正在 Ubuntu 10.04 上使用 NetBeans IDE 准备作业。我使用 g++ 作为 C++ 编译器。

错误信息:

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()'

还有我的相关代码:

迷宫.h

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

迷宫.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';
        }
    }
}
...
...

根据错误输出,我使用 stack 变量的每一行都有一个错误:未定义的引用。

堆栈.cpp

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

我用谷歌搜索了它,但无法解决问题。我认为我的包含顺序有问题,或者我以错误的方式使用了指针。

我也尝试过自己创建一个makefile,但结果并没有改变。我根据这个链接准备了这个makefile:http://www.cs.umd.edu/class/spring2002/cmsc214/Tutorial/makefile.html

这是我的生成文件:

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

我该如何克服这个错误?有什么想法吗?

【问题讨论】:

  • 请同时显示您的 Stack.cpp。
  • This question 和你的差不多,答案更完整。

标签: c++ templates gcc undefined-reference


【解决方案1】:

堆栈是一个模板。完整的定义必须放在它的头文件中。也就是说,不要将其分成 .h 和 .cpp 文件。

【讨论】:

  • 谢谢。这个简单的答案刚刚救了我的命:)
猜你喜欢
  • 1970-01-01
  • 2012-03-10
  • 2016-01-25
  • 1970-01-01
  • 2021-12-13
  • 2021-11-30
相关资源
最近更新 更多