//test.h 声明一个函数func()
void func();
//test.cpp 实现func函数
#include"test.h"
void func()
{
}
//main.cpp 调用func函数
int main()
{
func();
}
编译器会对以上代码进行处理:
test. cpp和main.cpp各自被编译成不同的.obj文件,在main.cpp中,调用了func函数,然而当编译器编译main.cpp时,它所仅仅知道的只是main.cpp中所包含的test.h文件中的一个关于void func();的声明。但是mian.cpp中并没有关于func()函数的代码。所以这个时候通过连接器寻找func的代码,找到以后将call f这个指令的调用地址换成实际的f的函数进入点地址。
但是如果通过模版实现则会出现编译错误
//test.h
template<class T>
class A
{
public:
A();
private:
int _a;
};
//test.cpp
#include "test.h"
template<class T>
A<T>::A()
:_a(0)
{}
//main.cpp
#include "test.h"
int main()
{
A<int> a;
return 0;
}
运行时会发生错误
为什么在使用模版时就会发生错误呢?
一般出现链接错误是因为声明了一个函数但是没有找到实体
解决方法是:取消分离编译,将声明和定义放在一起
//test.cpp
#include "test.h"
template<class T>
A<T>::A()
:_a(0)
{}
void func()
{
A<int> a1;
}