VS Code編譯調試C/C++(Windows平台)
- 引言
- 下載下傳安裝MinGW
- 編寫tasks.json檔案
- 編寫launch.json檔案
- 調試
引言
微軟的VS Code可以說是良心産品了,小巧輕便,适合中小型項目的開發(再也不用忍受Visual Studio的臃腫了)。VS Code本身是一個代碼編輯器而非完整的IDE,現把它編譯調試C/C++的方法記錄如下。
下載下傳安裝MinGW
這裡用MinGW作為C/C++編譯器。下載下傳:OSDN或SourceForge。
運作“MinGW Installer”,選擇需要安裝的元件(我安裝了如下項),菜單“Installation - Apply Changes”,等待下載下傳安裝完成。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZwpmLzQzM4UTOzUTM2IjMxgTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
将MinGW安裝目錄下的bin檔案夾添加到Path環境變量,如下(計算機 - 屬性 - 進階系統設定 - 環境變量)。這樣可以直接在指令行中使用g++等指令。
編寫tasks.json檔案
以C++為例,假設現在在VS Code中寫好了一個hello.cpp檔案。菜單“View - Command Palette”(Ctrl+Shift+P),搜尋并選擇“Tasks: Configure Task” - “others”,VS Code自動生成一個tasks.json檔案,将其修改如下。該檔案表示執行一個編譯任務,相當于指令行“
g++ -g hello.cpp
”。
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "echo",
"type": "shell",
"command": "g++",
"args": ["-g", "hello.cpp"]
}
]
}
編寫launch.json檔案
點選VS Code左側的Debug圖示,選擇“C++ (GDB/LLDB)”作為Configuration,VS Code自動生成一個launch.json檔案,将其修改如下。其中
"miDebuggerPath"
指定為“MinGW安裝目錄\bin\gdb.exe”,
"preLaunchTask": "echo"
對應tasks.json檔案中的
"label": "echo"
。這樣可以在調試前自動執行tasks.json檔案所說明的編譯任務,生成“a.exe”,對應launch.json檔案中的
"program": "${workspaceFolder}/a.exe"
。
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/a.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "D:\\ProgramFiles\\MinGW\\bin\\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "echo"
}
]
}
調試
在hello.cpp檔案中設定好斷點,按F5調試。應該可以調試成功啦。