Basic Usage
- Make sure compile file with
-goption, which mean turn on debugging with gdb- like this:
gcc -g main.cpp -o main
- like this:
Debugging with GDB
- Open file
- here are two way
gdb <file>gdb path/to/main
gdb->file path/to/main
- Show list
- use
lcommand to show source code with line number
- use
- breakpoint
- use
b <LINENUM>to add breakpoint, such asb 1add breakpoint at line 1 - or use
b <FUNCTIONNAME>to add breakpoint, such asb mainadd breakpoint at main function b <[file:]linenum|[file:]funciont>tb[reak]for a temporary breakpoint
- use
- Show breakpoint information
i bi for information, b for breakpointclear [[file:]function|[file:]lennum]to clean all breakpointrb[reak] REGEXPset breakpoint for all function matching REGEXPignore N COUNTignore bp 1 for COUNT times
- Inspect
- use
print, inspect or p [OPTION...] [EXP]to print value of expression EXP- use
p awill show information of variablea p [/FMT]print with specified formatp ARRAY[@len]print arrary with len elementp ['file'::]varprint var in specified file
- use
- use
- Delete breakpoint
d <BREAKPOINTNUM>break point num fromi bi binfo of breakpoint, information will be like a order list. If delete a pointid in the previous, the next point will just add in the end of the idlist.
- Run debug
r [args...]
- Gdb controler
n [N]for next line, one step debuggingsfor step into(one step)u|until [LINENUM|FUNC|ADDR|if condition]set args [parameter]for command line argsreturn <value>finish function and return<value>call <function>call specified function
- Finish function and continue
finishfor finish functioncfor continue until program exit or breakpoint
- Quit gdb
q
Tips
- You can write shell script in gdb
(gdb) shell <cmd>
- Set log
set logging on, which will copy output to filegdb.txt
- Watchpoints, Catchpoint… and so on
- You can use a watchpoint to stop execution whenever the value of an expression changes.
watch *<addr>orwatch <value>info watchpointsto print info of watchpoints
- Debug a running program
gdb -p <pid>
- Debug a core file
gdb <binary file> <core file>- System will no generate a core file by default. Because typically core files are very big. You can use
ulimitcommand to set unset the limit.
- 自定义脚本
1 | define print_list |