在 VSCode 中构建程序时如何指定包含路径?

KIY*_*IYZ 6 c compiler-errors visual-studio-code vscode-settings vscode-tasks

假设这是我的项目。

文件结构:

project_root
|-- inc
|   |-- header.h
|-- src
|   |-- helpers.c
|   |-- main.c
Run Code Online (Sandbox Code Playgroud)

header.h

#ifndef HEADER_H
# define HEADER_H

void    func(void);

#endif
Run Code Online (Sandbox Code Playgroud)

helpers.c

void    func()
{
    /* do something */
}
Run Code Online (Sandbox Code Playgroud)

main.c

#include "header.h"

int    main(void)
{
    func();
    return (0);
}
Run Code Online (Sandbox Code Playgroud)

c_cpp_properties.json

{
    "configurations": [
        {
            "name": "Mac",
            "includePath": [
                "${workspaceFolder}/inc",
            ],
            "defines": [],
            "macFrameworkPath": [
                "/System/Library/Frameworks",
                "/Library/Frameworks"
            ],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "gcc-x64"
        }
    ],
    "version": 4
}
Run Code Online (Sandbox Code Playgroud)

tasks.json

    "tasks": [
        {
            "type": "shell",
            "label": "gcc build active file",
            "command": "/usr/bin/gcc",
            "args": [
                "-g",
                "-Wall",
                "-Werror",
                "-Wextra",
                "-o0"
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}",
            ],
            "options": {
                "cwd": "${workspaceFolder}"
            },
            "group": {
            "kind": "build",
            "isDefault": true
            },
        }
    ],
    "version": "2.0.0"
}
Run Code Online (Sandbox Code Playgroud)

问题

当我在 VSCode 中构建我的程序时,出现以下错误。
project_root/src/main.c:xx:xx: fatal error: 'header.h' file not found

如何避免此错误?
(如何让 VSCode 的构建功能知道我的标头在哪里?)

我已经做了什么

我在 中配置了我的包含路径c_cpp_properties.json,所以我没有在 中获得波浪线main.c,我在其中包含了我的标题。

什么对我来说不是解决方案

我不想写#include "../inc/header.h"main.c,所以这不会是我的一个解决方案。

KIY*_*IYZ 7

specify the include paths in tasks.json, under the args property, using the -I flag.

{
    "tasks": [
        {
            "type": "shell",
            "label": "gcc build active file",
            "command": "/usr/bin/gcc",
            "args": [
                "-g",
                "-Wall",
                "-Werror",
                "-Wextra",
                "-o0",
                "-I${workspaceFolder}/inc",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}",
            ],
            "options": {
                "cwd": "${workspaceFolder}"
            },
            "group": {
            "kind": "build",
            "isDefault": true
            },
        }
    ],
    "version": "2.0.0"
}
Run Code Online (Sandbox Code Playgroud)

  • 我这样做了,它仍然说:“没有这样的文件或目录”。 (3认同)