我尝试编译一个C++模板类,该类分为.hpp
和.cpp
两个文件,但是出现了错误:
$ g++ -c -o main.o main.cpp
$ g++ -c -o stack.o stack.cpp
$ g++ -o main main.o stack.o
main.o: In function `main':
main.cpp:(.text+0xe): undefined reference to 'stack<int>::stack()'
main.cpp:(.text+0x1c): undefined reference to 'stack<int>::~stack()'
collect2: ld returned 1 exit status
make: *** [program] Error 1
以下是我的代码:
stack.hpp:
#ifndef _STACK_HPP
#define _STACK_HPP
template <typename Type>
class stack {
public:
stack();
~stack();
};
#endif
stack.cpp:
=>stack.cpp:
#include <iostream>
#include "stack.hpp"
template <typename Type> stack<Type>::stack() {
std::cerr << "Hello, stack " << this << "!" << std::endl;
}
template <typename Type> stack<Type>::~stack() {
std::cerr << "Goodbye, stack " << this << "." << std::endl;
}
main.cpp:
:主要的 C++ 源代码文件。#include "stack.hpp"
int main() {
stack<int> s;
return 0;
}
ld
当然是正确的:符号不在 stack.o
中。
这个问题 的答案没有帮助,因为我已经按照它说的做了。
这个或许有点帮助,但我不想把每个方法都移动到 .hpp
文件中,我不应该这样做,对吗?
唯一合理的解决方案是将 .cpp
文件中的所有内容都移到 .hpp
文件中,并简单地包含所有内容,而不是链接到一个独立的目标文件中吗?那看起来太丑陋了!如果那样的话,我可能还不如回到之前的状态,将 stack.cpp
改名为 stack.hpp
就行了。