栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

用VScode写C++代码遇到的include头文件和undefined reference to问题

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用VScode写C++代码遇到的include头文件和undefined reference to问题

新人学习用VScode写C++代码遇到的include头文件和undefined reference to问题

文章目录
  • 新人学习用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
#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;
}
问题: 1. 一开始写#include "test1.h"提示说找不到,按照提示加入includePath:

按住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"
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/973714.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号