【发布时间】:2013-12-09 08:49:18
【问题描述】:
继续获得未定义的参考,其他答案说应该是链接问题。我没有正确编译这个吗?还是代码有问题?我尝试将 main 放入 stack.cpp 并且它编译并运行良好,但我不确定还需要做什么来链接 main.o 和 stack.o 以及为什么它现在突然出现问题已添加此文件。
stack.h:
#ifndef STACK_INCLUDED
#define STACK_INCLUDED
#include <cstddef>
template<typename T> struct Node {
Node(T _data, Node<T> * _next) : data(_data), next(_next) {}
T data;
Node<T> *next;
};
template<class T>
class Stack {
private:
Node<T> *first;
public:
Stack(void);
bool isEmpty(void);
void push(T n);
T pop(void);
};
#endif
stack.cpp:
#include "stack.h"
template<class T>
Stack<T>::Stack(void) {
first = NULL;
}
template<class T>
bool Stack<T>::isEmpty(void) {
return first == NULL;
}
template<class T>
void Stack<T>::push(T n) {
Node<T> *oldfirst = first;
Node<T> *newfirst = new Node<T>(n, oldfirst);
first = newfirst;
first->next = oldfirst;
}
template<class T>
T Stack<T>::pop(void) {
T data = first->data;
first = first->next;
return data;
}
main.cpp:
#include <iostream>
#include "stack.h"
using namespace std;
int main(void) {
Stack<int> s;
if (!s.isEmpty()) {
cout << "not empty" << endl;
}
return 0;
}
尝试编译:
$ g++ stack.cpp -c
$ g++ main.cpp -c
$ g++ main.o stack.o
main.o: In function `main':
main.cpp:(.text+0x10): undefined reference to `Stack<int>::Stack()'
main.cpp:(.text+0x1c): undefined reference to `Stack<int>::isEmpty()'
collect2: ld returned 1 exit status
【问题讨论】:
标签: c++ compilation compiler-errors