Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux GDB 偵錯器完整指南:從單執行緒到多執行緒進階技巧

編輯:Linux 教學

GDB (GNU Debugger) 是 Linux 下最強大的命令列偵錯工具。本文系統整理常用指令、操作流程與多執行緒偵錯技巧,助你快速定位程式錯誤。

前置條件:編譯時加入偵錯資訊

gcc -g program.c -o program   # 或 g++ -g
# -g 參數嵌入符號表與行號資訊,GDB 才能對應原始碼

一、常規偵錯核心指令速查表

指令縮寫功能常用範例
listl顯示原始碼(預設 10 行)list main, list 20, list -
breakb設定中斷點break 15, break func, break file.c:20
runr啟動程式至中斷點run arg1 arg2
nextn單步執行(不進入函式)類似 VS F10
steps單步執行(進入函式)類似 VS F11
continuec繼續執行至下一中斷點
printp列印變數值p var, p *ptr, p/x addr
backtracebt查看呼叫堆疊bt full 含區域變數
infoi查看偵錯資訊info break, info locals, info threads
edite編輯當前行原始碼
whatis查看變數型別whatis var
helph指令說明help break
quitq離開 GDB

二、載入與啟動模式

  • gdb ./program:偵錯可執行檔。
  • gdb ./program core:事後分析 core dump。
  • 啟動後輸入 run 開始執行。

三、原始碼修改後熱重載(不重啟 GDB)

在 GDB 內直接輸入 make 重新編譯,GDB 會自動重新載入符號表,**保留已設定的中斷點**,極大提升效率。

四、多執行緒偵錯進階指令

指令縮寫功能
info threadsinfo thr列出所有可偵錯執行緒,* 表當前執行緒
thread IDthr ID切換至指定 ID 執行緒
thread apply ID1 ID2 cmdthr apply讓指定執行緒執行 cmd
thread apply all cmdthr apply all讓所有執行緒執行 cmd(如 bt)
set scheduler-locking off|on|step控制單步時其他執行緒行為

scheduler-locking 三種模式

  • off(預設):所有執行緒並發執行。
  • on:僅當前執行緒執行,其他凍結。
  • step:單步時(除 next 跨函式外)僅當前執行緒執行,適合精準追蹤。

實用小技巧

  • Enter 重複上一指令(連續單步極快)。
  • display var:每次停下自動顯示變數值。
  • watch expr:資料觀察點,表達式值改變即中斷。
  • 搭配 TUI 模式(Ctrl+X Ctrl+A)分割視窗顯示原始碼。
Copyright © Windows教程網 All Rights Reserved