VS Code编译file not found问题

最近在使用visual studio code的时候,编写c++代码,往往需要引入第三方的头文件,如下所示:

#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
// 省略余下代码

但是如果这些头文件的路径不在默认的搜索路径中(/usr/include或者/usr/local/include),那么在编译的时候,就会报错,提示“file not found”,按照网上搜索的很多方法,都是通过修改c_cpp_properties.json,在includePath中加入相应的路径即可(shift+command+p,选择C/C++: Edit Configurations即可打开)。但是实际测试发现,即使在includePath中添加了路径,也会报同样的错误。个人怀疑这个地方的includePath,实际并没有添加到task的path中。

经过测试发现,如果头文件指定绝对路径或者想对路径是ok的,如下所示:

// 相对路径
#include "../../local/rapidjson/document.h"
// 绝对路径
#include "/home/user/cpp/local/rapidjson/document.h"

但是一旦头文件地址有所变动,就需要改动代码,非常麻烦。因此,我们需要修改配置文件来实现显示增加头文件的搜索路径。

我们可以通过修改task.json来实现(shift+command+p,Tasks: Configure Task),这里以我自己的测试为例:

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [
    {
      "label": "ws-test",
      "type": "shell",
      "command": "g++",
      "args": [
        "-Wall","-std=c++11", "-g",
        "main.cpp",
        "DocumentTest.cpp","DocumentTest.h",
        "CppTest.cpp","CppTest.h",
        "-I", "/Users/ws/project/c/local"
      ],
      "group": {
        "kind": "build",
        "isDefault": true
      },
      "problemMatcher": [
        "$gcc"
      ],
      "isShellCommand": true,
    }
  ]
}

这里,就是通过增加"-I", "/Users/ws/project/c/local",来显示指定头文件的搜索路径,其实该配置文件就相当于自动执行了如下命令:

g++ -Wall -std=c++11 -g main.cpp DocumentTest.cpp DocumentTest.h CppTest.cpp CppTest.h -I /Users/ws/project/c/local

在使用g++命令编译时,-I表示“Add directory to include search path”,即指定搜索路径。这样,再使用该task配置进行编译的时候,就不会再出现“file not found”的问题了,搞定。

  • 7
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值