最基本的編譯時要加"-g",把 debugging information 編譯進去,否則印不出什麼資訊來。再來就是不要做 optimize,不然程式碼行數會對不上。
$ gcc -g -o hello hello.c
啟動 GDB
$ gdb ./hello
必要時加入"-d (dirctory)"的參數,指定 source code 的位置
$ gdb -d /home/brian/test ./hello
若程式已經在執行了,可以先查詢 pid,然後用 attach 的方式。記得 binary 的要跟正在 run 的 program 一致
$ gdb ./hello 12238
進入GDB後執行程式
(GDB) run
若要帶參數的話
run (init parameter)
Ex:
(GDB) run -h localhost -p 8080
Breakpoint
設定中斷點
b (filename):(line num)
Ex:
(GDB) b hello.c:5
列出目前的中斷點
(GDB) info b
Num Type Disp Enb Address What
1 breakpoint keep y 0x000000000040049c in main at hello.c:5
移除中斷點
d (breakpoint id)
Ex:
(GDB) d 1
列出當下的狀況
列出 function stack (Back trace)
(GDB) bt
#0 hello () at hello.c:9
#1 0x00000000004004cf in main () at hello.c:14
列出更詳細的資訊,包含 variable 的值
(GDB) bt full
#0 hello () at hello.c:9
i = 0
#1 0x00000000004004cf in main () at hello.c:14
No locals.
列印變數
p (variable)
Ex:
(GDB) p iValue
(GDB) p *stEmployee
切換 frame。要列印區域變數時,必須要切換到正確的 frame
f (frame num)
EX:
(GDB) f 3
流程控制
Step over (不會進 function)
(GDB) n
Step into (會跳入 function)
(GDB) s
Continue
(GDB) c
Signal Handle
handle (signal) (operation)
Operation 預設為 stop print noignore,也就是遇到 signal 時,GDB 會先攔截,並中斷程式,必要時可以改為 nostop noprint,讓程式本身去處理 signal。若下達 ignore 則是讓程式忽略此 signal。
(GDB) handle SIGUSR nostop noprint
列出目前 signal 設定的狀態
(GDB) i handle
Signal Stop Print Pass to program Description
SIGHUP Yes Yes Yes Hangup
SIGINT Yes Yes No Interrupt
SIGQUIT Yes Yes Yes Quit
SIGILL Yes Yes Yes Illegal instruction
SIGTRAP Yes Yes No Trace/breakpoint trap
有關 signal 的部分可以參考
http://sourceware.org/gdb
Thread
查看目前在哪個 thread
(GDB) thread
切換 thread
(GDB) thread 3
列出所有 thread 的 function stack
(GDB) thread apply all bt
(GDB) thread apply all bt full
Ref:
Examining the Symbol Table