- VS Code只是個文字編輯器+前端除錯介面,預設空空如也,不負責幫忙組建(Build) 程式,也沒自帶編譯器(Compiler)與除錯器(Debugger)
- 所以要先自己在作業系統中裝好編譯器與除錯器
- gcc、make、lldb
- 接著"設定"在VS Code中下指令時對應的呼叫行為
- 組建(Task:Run Build Task)指令
- 透過tasks.json設定組建工作,該呼叫何編譯器、引數、路徑...等
- 除錯(Debug:Start Debuggin)指令
- 透過launch.json設定除錯工作,該呼叫何除錯器、引數、路徑...等
Step1:寫程式時好用Intellisense
參考官方指引,安裝:
接著按F1,命令下:>C/Cpp:Edit Configurations,它會幫你產c_cpp_properties.json,主要提供 編寫程式時的標頭檔索引、找尋、Intellisense相關功能所需參數,與建置與除錯毫無關係,先來一個基本的Hello World:
#include<stdio.h>
int main()
{
printf("hello world");
return 0;
}
Step2:搞定建置工作
按F1,命令下:>Tasks:Configure Default Build Task,接著會問你要選擇何樣板,這次打算以make編譯,因此選擇Others,來自己編命令內容,決定後產出預設tasks.json
接著我們把tasks.json改寫成這樣,相當於在shell中下#make all:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"taskName": "make",
"type": "shell",
"command": "make",
"args": [
"all"
]
}
]
}
當然要有對應的makefile:all: gcc -g main.c -o main註:gcc必須加上-g選項,才能編譯出能夠Debug的執行檔
因為tasks.json是可以放進多組工作組態的(Task Configuration),若要一鍵執行建置得要指名是何組態為預設建置工作:按F1, Tasks: Configure Defualt Build Task,tasks.json變成這樣,第二組組態"echo"是故意拿來對比測試的:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"taskName": "make",
"type": "shell",
"command": "make",
"args": [
"all"
],
"group": {
"kind": "build",
"isDefault": true
}
},
{
"taskName": "echo",
"type":"shell",
"command": "echo hello"
}
]
}
最後試一下實際一鍵呼叫建置工作,工作->執行建置工作:滴滴答答得到一個main
Step3:搞定除錯工作
偵錯->新增組態,選擇C/C++:(lldb)Launch,系統會幫你產好launch.json,並寫好一組名為"(lldb)Launch"的組態,此時再修改幾處就可以直接用了:
- 加上preLaunchTask欄位,此欄位代表在偵錯前要呼叫何工作(Task),偵錯前當然要先建置出最新版本,所以這裡填"preLaunchTask": "make",會以task.json內的名為"make"的組態進行工作
- program指向你要除錯的執行檔,這裏就填"program": "${workspaceRoot}/main",因為在方才的Makefile內我們最終會生出名為"main"的可執行檔
{
"version": "0.2.0",
"configurations": [
{
"name": "(lldb) Launch",
"type": "cppdbg",
"request": "launch",
"preLaunchTask": "make",
"program": "${workspaceRoot}/main",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": true,
"MIMode": "lldb"
}
]
}
最後試一下,F5啟動除錯,果然建置工作先被帶出:除錯器讓程式卡在第6行,如果gcc沒加-g選項是不會停下來的,打完收工
後記1:專案存在Github




沒有留言:
張貼留言