Linux環境下 使用VS code debugging C設定步驟

tags: VS code

問題:

在實做Lab0作業時,

依照GUN/Linux開發工具共筆中的編輯器:Visual Studio Code 偵錯教學去設定debug 環境
發現組態用GDB 設定時,在debug mode環境下,無法同時藉由終端機下command和debug mode程式連動

詳見實驗操作紀錄 vs code debug test


解決辦法

參考 Debugging C/C++ with Visual Studio Code 方法

step1. 在vs code開啟終端機頁面

先下make指令,產出qtest執行檔


step2.debug mode改用 C++(GDB/LLDB) 設定

選擇gcc-建置及偵錯使用中的檔案


在launch.json組態設定預設為

修改launch.json組態
step3-1. 確認

"request": "launch",

step3-2.

"program": "${fileDirname}/qtest", //改成我們指定的指定 qtest 執行檔名稱路徑

step3-3.砍掉
​​​​ "preLaunchTask": "gcc build active file",
​​​​ "miDebuggerPath": "/usr/bin/gdb"

修改後如下

launch.json

{ // 使用 IntelliSense 以得知可用的屬性。 // 暫留以檢視現有屬性的描述。 // 如需詳細資訊,請瀏覽: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "gcc - 建置及偵錯使用中的檔案", "type": "cppdbg", "request": "launch", "program": "${fileDirname}/qtest", //指定 qtest 執行檔名稱路徑 "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "gdb", "setupCommands": [ { "description": "啟用 gdb 的美化顯示", "text": "-enable-pretty-printing", "ignoreFailures": true } ], } ] }

step4.

最後按debug mode下,也能跨到console.c執行,且能在終端機一邊下command,同時trace code執行過程做觀察

實驗結果紀錄 vs code debug test2

補充說明

若想重設vs code組態設定

step1.在專案文件夾中 開啟顯示隱藏檔

step2.將隱藏文件夾.vscode刪除 即能重新配置launch.json組態設定

How to debug C code with GDB in VSCode (Linux)


Dennis40816的 Lab0

VSCode gdb

在 lab0-c 中,直接使用 gdb 對 qtest 除錯會遇到 SIGALRM 導致超時。而透過 python scripts/debug.py -d 則可以啟動已經忽略 SIGALRM 的 gdb。同理我們也能在 .vscode/launch.jsonsetupCommands 設定:

"setupCommands": [
    {
        "description": "Ignore SIGALRM signal",
        "text": "handle SIGALRM ignore",
        "ignoreFailures": true
    },
    {
        "text": "backtrace",
        "ignoreFailures": true
    },
]

巨集在前處理期間就被展開,故 gdb 無法像函式一樣使用它們。這對於常用的巨集 (e.g., container_of ) 稍有不便。我們當然能夠在 gdb 裡面暴力打出所有已知資訊,透過類似:

(gdb) p (struct my_container *)((char *)my_member_ptr - offsetof(struct my_container, member))

獲得我們要的 debug 資訊,但我們也能透過 python 的 gdb package 去實作實用的函式,進而降低使用時的複雜度。如果你也想使用客製化且能使用 VSCode 除錯介面的 gdb,請參考 〈Linux2025q1: Toolchain Write-Up〉 commit cb104ee。裡面介紹了如何實作 container_of 等功能,讓你 debug 更輕鬆。

Select a repo