用CLion初学c++,学习到分离式编译时,发现一直报错。
有包含main函数的gamePlay.cpp文件和函数定义的game.cpp文件以及game.h文件,在gamePlay.cpp文件中引入了
#include "game.h"
但是编译器报以下错误:
Undefined symbols for architecture x86_64:
"inputGameName(Game*, int)", referenced from:
_main in gamePlay.cpp.o
"sort(Game*, int)", referenced from:
_main in gamePlay.cpp.o
"display(Game const*, int)", referenced from:
_main in gamePlay.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
看起来大概是没有编译器没有调用到game.cpp中的函数。
然后我试了一下加上
#include "game.cpp"
结果程序运行成功。
最终主函数是这样的
#include "game.h"
#include "game.cpp"
int main() {
cout << "请输入5个你喜爱的游戏的名称,并给他们评分:" << endl;
Game games[SIZE] = {};
inputGameName(games, SIZE);
sort(games, SIZE);
display(games, SIZE);
return 0;
}
看来主程序文件还要再引入函数文件。
顺便一提,在CMakeLists.txt文件中还要引入头文件:
include_directories(/Users/apple/hello/c++/ch_two/game.h) //括号中为.h文件的绝对路径