- 新人学习用VScode写C++代码遇到的include头文件和undefined reference to问题
- 环境:
- 项目:
- 问题:
- 1. 一开始写#include "test1.h"提示说找不到,按照提示加入includePath:
- 2. 加了includePath还是报错说找不到test1.h
- 3. 头文件找到了又报错undefined reference to `sayHello()'
Win10,安装了WLS2+Ubuntu20.04(不用mingw是因为没有更新)。
VScode安装了Remote SSH插件和C++插件。
就一个test.cpp文件引用libs目录下的test1.h文件。
先给最终代码:
// test.cpp #include问题: 1. 一开始写#include "test1.h"提示说找不到,按照提示加入includePath:#include "libs/test1.h" //写成"test1.h"会报找不到 using namespace std; int main(){ cout<<"ddddn"; sayHello(); } // test1.h int sayHello(); //test1.cpp #include #include "test1.h" int sayHello(){ std::cout<<"helllxxxxxxxxxon"; return 0; }
按住ctrl+shift+p,出来一个窗口,输入c++,我选择JSON配置,在includePath中增加头文件所在目录"${workspaceFolder}/libs"。
// c_cpp_properties.json
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"${workspaceFolder}/libs"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "gnu17",
"cppStandard": "gnu++14",
"intelliSenseMode": "linux-gcc-x64"
}
],
"version": 4
}
2. 加了includePath还是报错说找不到test1.h
把#include "test1.h"改成#include “libs/test1.h”
3. 头文件找到了又报错undefined reference to `sayHello()’原因是没有编译test1.cpp文件,只编译了test.cpp文件,需要增加编译参数"${fileDirname}/libs/*.cpp":
// tasks.json
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ 生成活动文件",
"command": "/usr/bin/g++",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"${fileDirname}/libs/*.cpp",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "调试器生成的任务。"
}
],
"version": "2.0.0"
}



