每次 print 輸出的值自動記錄在值歷史中,可引用歷史值。
| 語法 | 含義 |
|---|---|
$ | 最近一次的值 |
$n | 第 n 個歷史值($1 為最早) |
$$ | 倒數第二個值 |
$$n | 倒數第 n 個值 |
$_ | x 命令最後顯示的地址 |
$__ | x 命令最後顯示地址處的值 |
$_exitcode | 被調試程序退出碼 |
$bpnum | 最後設置的斷點編號 |
(gdb) p argc $1 = 1 (gdb) p $ $2 = 1 (gdb) p $$ $3 = 1 (gdb) show values $1 = 1 $2 = 1 $3 = 1
用戶自定義變量,以 $ 開頭,由字母數字組成,類型自動推導。
(gdb) set $abc = 100 (gdb) p $abc $4 = 100 (gdb) set $ptr = (int*)0x8048000 (gdb) p *$ptr
默認保存至 ~/.gdb_history,會話結束時寫入。
(gdb) set history save on # 啟用保存 (gdb) set history size 512 # 歷史條數 (gdb) set history filename /path/file # 自定義文件 (gdb) set history expansion on # 開啟歷史擴展(!號引用)
GDBHISTFILE 可覆蓋默認歷史文件路徑。
.gdbinitGDB 啟動時自動執行的腳本,載入順序:
$HOME/.gdbinit(用戶級)-x 指定的文件./.gdbinit(項目級,需 set auto-load safe-path 允許)# 禁用分頁 set pagination off # 顯示行號 set print frame-arguments all # 定義常用別名 define hook-run echo \n=== Program Started ===\n end
(gdb) define mycmd Type commands for definition of "mycmd", one per line. End with a line saying just "end". > info registers > x/10i $pc > end
(gdb) document mycmd Type documentation for "mycmd". End with a line saying just "end". > Show registers and next 10 instructions > end
(gdb) mycmd (gdb) help mycmd Show registers and next 10 instructions
# 打印鏈表
define print_list
set $node = $arg0
while $node != 0
print $node->data
set $node = $node->next
end
end
document print_list
Print linked list starting at node pointer (arg0)
end
# 打印二叉樹中序
define print_tree
if $arg0 != 0
print_tree $arg0->left
print $arg0->val
print_tree $arg0->right
end
end
$)避免重複輸入複雜表達式。$var)存儲中間結果、指針、計數器。.gdbinit 實現項目級/用戶級自動化配置。