1
见下面我的演示代码:A怪 '未定义参考' 错误使用g ++
b.hpp:
#ifndef B_HPP
#define B_HPP
namespace debug {
class test {
public:
template <class T> void foo(T a);
private:
int a;
};
}
#endif
b.cpp:
#include <iostream>
#include "b.hpp"
namespace debug {
template <class T>
void test::foo(T a) {
std::cout << "debug" << std::endl;
}
}
testb.cpp:
include "b.hpp"
int main(int agrc, char *argv[])
{
debug::test a;
int c = 5;
a.foo(c);
return 0;
}
我编译它与
g++ -std=c++11 testb.cpp b.cpp'
,并得到一个错误:
/tmp/ccnjR5S4.o: In function `main':
testb.cpp:(.text+0x1c): undefined reference to `void debug::test::foo<int>(int)'
collect2: error: ld returned 1 exit status
什么问题?
如果我把主函数放在b.cpp中并编译b.cpp,没关系。为什么?
谢谢!
简短的回答,编译器永远不会实例化'测试:: foo'这样的功能在任何时候都不存在。为什么它不能实例化?因为完整的定义不可用。 –
greatwolf