当我使用模板为类编写C++代码并在源(CPP)文件和标题(H)文件之间拆分代码时,在链接最终可执行文件时会出现大量"未解析的外部符号"错误,尽管目标文件正确构建并包含在链接中.这里发生了什么,我该如何解决?
我在这里读过你必须包含.h文件而不是.cpp文件,因为否则会出错.所以举个例子
main.cpp中
#include <iostream>
#include "foop.h"
int main(int argc, char *argv[])
{
int x=42;
std::cout << x <<std::endl;
std::cout << foo(x) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
foop.h
#ifndef FOOP_H
#define FOOP_H
int foo(int a);
#endif
Run Code Online (Sandbox Code Playgroud)
foop.cpp
int foo(int a){
return ++a;
}
Run Code Online (Sandbox Code Playgroud)
作品,但如果我更换#include "foop.h"与#include "foop.cpp"我得到一个错误(使用开发C++ 4.9.9.2,Windows中):
multiple definition of foo(int)
first defined here
Run Code Online (Sandbox Code Playgroud)
为什么是这样?