一行代码解决vscode编译C++多文件时 undefined reference to “XXX” 问题

项目场景:

  • 使用vscode编译C++多文件

问题描述

编译运行时界面弹出警告:
一行代码解决vscode编译C++多文件时 undefined reference to “XXX” 问题_第1张图片
终端提示出现错误:

正在启动生成...
E:\x86_64-8.1.0-release-win32-seh-rt_v6-rev0\mingw64\bin\g++.exe -fdiagnostics-color=always -g G:\Code\C++hexinbiancheng\test_20\1.cpp -o G:\Code\C++hexinbiancheng\test_20\coin\1.exe -fexec-charset=GBK
c:\user\default\AppData\Local\Temp\ccJ7D1Gm.o: In function `isInCirle(Circle&, Point&)':
G:/Code/C++hexinbiancheng/test_20/1.cpp:74: undefined reference to `Circle::getCenter()'
G:/Code/C++hexinbiancheng/test_20/1.cpp:74: undefined reference to `Point::getX()'
G:/Code/C++hexinbiancheng/test_20/1.cpp:74: undefined reference to `Point::getX()'
G:/Code/C++hexinbiancheng/test_20/1.cpp:74: undefined reference to `Circle::getCenter()'
G:/Code/C++hexinbiancheng/test_20/1.cpp:74: undefined reference to `Point::getX()'
G:/Code/C++hexinbiancheng/test_20/1.cpp:74: undefined reference to `Point::getX()'
G:/Code/C++hexinbiancheng/test_20/1.cpp:74: undefined reference to `Circle::getCenter()'
G:/Code/C++hexinbiancheng/test_20/1.cpp:74: undefined reference to `Point::getY()'
G:/Code/C++hexinbiancheng/test_20/1.cpp:74: undefined reference to `Point::getY()'
G:/Code/C++hexinbiancheng/test_20/1.cpp:74: undefined reference to `Circle::getCenter()'
G:/Code/C++hexinbiancheng/test_20/1.cpp:74: undefined reference to `Point::getY()'
G:/Code/C++hexinbiancheng/test_20/1.cpp:74: undefined reference to `Point::getY()'
G:/Code/C++hexinbiancheng/test_20/1.cpp:77: undefined reference to `Circle::getR()'
G:/Code/C++hexinbiancheng/test_20/1.cpp:77: undefined reference to `Circle::getR()'
c:\user\default\AppData\Local\Temp\ccJ7D1Gm.o: In function `main':
G:/Code/C++hexinbiancheng/test_20/1.cpp:101: undefined reference to `Point::setX(int)'
G:/Code/C++hexinbiancheng/test_20/1.cpp:102: undefined reference to `Point::setY(int)'
G:/Code/C++hexinbiancheng/test_20/1.cpp:106: undefined reference to `Circle::setR(int)'
G:/Code/C++hexinbiancheng/test_20/1.cpp:108: undefined reference to `Point::setX(int)'
G:/Code/C++hexinbiancheng/test_20/1.cpp:109: undefined reference to `Point::setY(int)'
G:/Code/C++hexinbiancheng/test_20/1.cpp:110: undefined reference to `Circle::setCenter(Point)'
collect2.exe: error: ld returned 1 exit status

生成已完成,但出现错误。

原因分析:

  • 使用VSCode时,在同一文件夹下,存在多个文件时,编译器无法找到引用的.h文件定义

解决方案:

  1. 打开.VScode\tasks.json一行代码解决vscode编译C++多文件时 undefined reference to “XXX” 问题_第2张图片

  2. 仅需要更改11行一行代码 "${fileDirname}\\*.cpp",
    一行代码解决vscode编译C++多文件时 undefined reference to “XXX” 问题_第3张图片

  3. tasks.json文件中的args参数问题,由于参数${file}代表的是被编译的当前文件,而多文档包含多个文档,编译器无法找到当前文件所引用的相关文件,因此将参数改为${fileDirname}\\*.cpp代表可以编译当前目录下的所有.cpp文件。如果是编译.c文件则将参数改为${fileDirname}\\*.c

  4. 参考文章:知乎链接

你可能感兴趣的:(c++,vscode,开发语言)