1诗越、背景
??根目錄下含有3個文件夾砖瞧,其中.vscode用于存放配置文件,a存放頭文件a1.h嚷狞,b存放源文件b1.c块促。b1.c引用a1.h,現(xiàn)希望編譯運行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用于調(diào)試運行代碼裂允。
3损离、settings.json是runcode的配置文件,用于直接點擊運行代碼绝编。
??VSCode工作目錄是根目錄(C:\Users\Administrator\Desktop\test)僻澎,但b1.c在子文件夾b中貌踏,故其工作目錄是根目錄下的b文件夾(C:\Users\Administrator\Desktop\test\b),兩者并不相同窟勃,在引用外部文件的路徑需特別注意祖乳。
??對于調(diào)試運行,VSCode默認(rèn)使用其工作目錄C:\Users\Administrator\Desktop\test秉氧。而對于runcode眷昆,由于編譯命令中含跳轉(zhuǎn)指令cd,運行程序時會自動跳轉(zhuǎn)到b1.c所在文件夾汁咏,故直接運行時其工作目錄是C:\Users\Administrator\Desktop\test\b亚斋。
3、實現(xiàn)
??由于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不在同一文件夾,也不在根目錄下轰驳,故調(diào)試時需在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"
}
調(diào)試運行結(jié)果:
??
??同理,應(yīng)在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",
}
}
直接運行結(jié)果:
4冒黑、總結(jié)
??使用VSCode時,最好確保VSCode與.c的工作目錄一致勤哗,即將.c放在根目錄下抡爹。若工作目錄不一致,引用外部文件時最好使用絕對地址芒划,運行時需注意在settings.json或tasks.json添加.h所在文件夾路徑冬竟。只在c_cpp_properties.json添加.h所在文件夾路徑,最多是在寫代碼不提示包含路徑錯誤而已民逼,對運行代碼時引用外部文件不起作用泵殴。