第一步,下載vscode,在插件庫中搜索關鍵字c,選擇第一個插件進行安裝。https://code.visualstudio.com/
第二步,下載MinGW,並在環境變量中將MInGW bin文件夾配置進系統環境變量。https://osdn.net/projects/mingw/releases/
下面的幾步如果喜歡看英文的話推薦看微軟官方的英文文檔。https://code.visualstudio.com/docs/languages/cpp
如果不喜歡的話,就聽我慢慢道來
用vscode打開一個文件夾,這個文件夾就是我們的工程文件夾
打開vscode命令行 (點擊左下角設置按鈕,第一個選項 Command Palette) 輸入 C/Cpp:Edit Configurations 然後創建出來 c_cpp_properties.json 文件 我們編輯這個文件 成爲下圖的格式
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"compilerPath": "D:\\MinGW\\bin\\gcc.exe",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "clang-x64"
}
],
"version": 4
}
其中,比較關鍵的參數就是 "includePath" 這個鍵,這個是標識你工程所用的頭文件所在的地方,這裏就是打開的工程文件夾。
還有一個比較關鍵的參數是 "compilerPath": "D:\\MinGW\\bin\\gcc.exe" 這個參數是標識你編譯器的位置
剩下的基本不用改,"intelliSenseMode": "clang-x64",這個參數我說一下,是設置自動 智能感知補全的
有人會問,那stdio.h像這種庫的頭文件還要一個一個添加至"includePath"中嗎? 答案是不用,
因爲"compilerPath" 指定MinGW爲默認編譯器之後,這個c插件就會自動找到MInGW下的include目錄,就不用手動再添加了,添加的只是自定義的頭文件。
繼續在命令行輸入Tasks: Configure Tasks 生成 task.json 這個是構建項目時用的(就是用來生成.exe控制檯程序的),將文件改成如下格式
{
"version": "2.0.0",
"tasks": [
{
"label": "build hello world",
"type": "shell",
"command": "g++",
"args": [
"helloworld.cpp", "-g","-o","helloworld.exe"
]
}
]
}
其中args是g++ 構建時的命令行,"args": [ "helloworld.cpp", "-g","-o","helloworld.exe"] 第一項是編譯項,“-g” 是提供調試信息,爲了能進行debbuger,“-o”指定編譯連接後生成的文件 這裏指定的是helloworld.exe
在命令行輸入Tasks: Run Build Task 然後添加 group信息到task,json 中,task.json內容如下所示
{
"version": "2.0.0",
"tasks": [
{
"label": "build hello world",
"type": "shell",
"command": "g++",
"args": [
"helloworld.cpp",
"-g",
"-o",
"helloworld.exe"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
在打開文件夾下新建一個helloworld.cpp(Ctrl+N 並保存至 打開的文件夾下面)
#include<stdio.h>
#include<stdlib.h>
int main()
{
printf("Hello World!");
system("pause");
}
在Debug下面選一個Launcher (選擇C++ (GDB/LLDB)這一項)生成launch.json 將文件改成如下格式
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/helloworld.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "D:\\mingw\\bin\\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "build hello world"
}
]
}
其中,miDebuggerPath這一項 是寫的你的調試器路徑;preLaunchTask這一項對應 task.json 中的label一項(因爲調試是在構建完成之後,要不你調試啥)。“program”指定要調試的文件,就是構建生成的.exe文件
ok,一切都完成了,點擊debug調試按鈕,開始調試運行
注意多文件編譯時只需要修改task.json(構建文件)文件中的args參數就可以了,這裏舉一個例子
{
"version": "2.0.0",
"tasks": [
{
"label": "build hello world",
"type": "shell",
"command": "g++",
"args": [
"source/helloworld.cpp",
"source/main.cpp",
"-g",
"-o",
"main.exe"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
args前兩個是要編譯鏈接的 文件,"-o"指定生成的文件是main.exe
好了,給個github地址 裏面有多文件編譯的實例 https://github.com/ZhangZhiShuo/vscode-MinGW- 解壓即可