VS Code:编译运行根目录下不同文件夹中的文件


1、背景

  根目录下含有3个文件夹,其中.vscode用于存放配置文件,a存放头文件a1.h,b存放源文件b1.c。b1.c引用a1.h,现希望编译运行b1.c。

文件目录:

a1.h:

int g_a = 1;

b1.c:

#include <stdio.h>
#include <a1.h>

int main()
{
    printf("%d", g_a);
    return 1;
}

2、分析

.vscode下的配置文件:
1、c_cpp_properties.json一般用于添加包含路径,方便程序员编写代码时直接引用外部文件。该文件对编写代码有用,引用文件时不会提示错误,但对运行代码用处不大。
2、launch.json和tasks.json用于调试运行代码
3、settings.json是runcode的配置文件,用于直接点击运行代码

  VSCode工作目录是根目录(C:\Users\Administrator\Desktop\test),但b1.c在子文件夹b中,故其工作目录是根目录下的b文件夹(C:\Users\Administrator\Desktop\test\b),两者并不相同,在引用外部文件的路径需特别注意。

  对于调试运行,VSCode默认使用其工作目录C:\Users\Administrator\Desktop\test。而对于runcode,由于编译命令中含跳转指令cd,运行程序时会自动跳转到b1.c所在文件夹,故直接运行时其工作目录是C:\Users\Administrator\Desktop\test\b

3、实现

  由于b1.c引用a1.h,故需要在c_cpp_properties.json -> configurations -> includePath添加a1.h所在文件夹路径。

c_cpp_properties.json:

{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**",
                "C:/Users/Administrator/Desktop/test/a"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "windowsSdkVersion": "10.0.18362.0",
            "compilerPath": "C:/Program Files/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.24.28314/bin/Hostx86/x86/cl.exe",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "msvc-x64"
        }
    ],
    "version": 4
}

  
  由于运行时a1.h与b1.c不在同一文件夹,也不在根目录下,故调试时需在tasks.json -> tasks -> args加上"-I",“a1.h所在文件夹路径”。

tasks.json:

{
    "tasks": [
        {
            "type": "shell",
            "label": "gcc.exe build active file",
            "command": "C:\\Mingw-w64\\mingw32\\bin\\gcc.exe",
            "args": [
                "-g",
                "${file}",
                "-I",
                "C:/Users/Administrator/Desktop/test/a",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "C:\\Mingw-w64\\mingw32\\bin"
            }
        }
    ],
    "version": "2.0.0"
}

调试运行结果:

  
  同理,应在settings.json -> code-runner.executorMap -> c加上-I a1.h所在文件夹路径。

settings.json:

{
    "code-runner.executorMap": {
        "c": "cd $dir && gcc $fileName -I C:/Users/Administrator/Desktop/test/a -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
    }
}

直接运行结果:

4、总结

  使用VSCode时,最好确保VSCode与.c的工作目录一致,即将.c放在根目录下。若工作目录不一致,引用外部文件时最好使用绝对地址,运行时需注意在settings.json或tasks.json添加.h所在文件夹路径。只在c_cpp_properties.json添加.h所在文件夹路径,最多是在写代码不提示包含路径错误而已,对运行代码时引用外部文件不起作用。

猜你喜欢

转载自blog.csdn.net/qq_34801642/article/details/106419763