VSCode编译c++时自定义头文件报错
VSCode编译C++时自定义头文件报错fatal error: add.h: No such file or directory#include "add.h"^~~~~~~compilation terminated.
·
报错内容如下:
fatal error: add.h: No such file or directory
#include "add.h"
^~~~~~~
compilation terminated.
项目结构如下:
add.h 文件内容:
add.cpp 文件内容:
main.cpp 文件内容:
以下解决方法不使用CodeRunner插件而选择VSCode自带的功能,
修改项目文件夹下.vscode文件夹中的task.json文件:
修改前配置:
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++.exe 生成活动文件",
"command": "D:\\cdk\\mingw64\\bin\\g++.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "调试器生成的任务。"
}
],
"version": "2.0.0"
}
修改后:
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++.exe 生成活动文件",
"command": "D:\\cdk\\mingw64\\bin\\g++.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${workspaceFolder}\\src\\**.cpp",
"-I",
"${workspaceFolder}\\inc",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "调试器生成的任务。"
}
],
"version": "2.0.0"
}
上述操作实际上等价于g++命令
g++ -g ${workspaceFolder}/src/**.cpp -I ${workspaceFolder]/inc -o ${fileBasenameWithoutExtension}.exe
即:把-g后面的参数替换为src文件夹下所有.cpp文件(必须加上所有涉及的源文件,不然即使找到头文件也会报错),-I 后的参数替换为头文件所在的inc文件夹
修改完task.json参数后,执行编译并运行时,选择Run C/C++ File
至此,编译成功!
更多推荐
已为社区贡献1条内容
所有评论(0)