Basic GDB commands

1 minute read

Published:

Using GDB

Learn how to use GDB to debug your program.

compile with debug info

gcc -g -o test test.c # 直接编译为debug版本

# 或者在正常编译完成后再编译为debug版本
gcc -o test test.c
gcc -g test

run gdb

gdb test

basic commands

# run the program
run # r

# quit gdb
quit # q

# list the source code
list # l

# set a breakpoint
# break can break at a function or a line
break main # b main
break 10 # b 10

# show breakpoints
info breakpoints # i b

# delete a breakpoint
delete 1 # d 1

# continue the program
continue # c

# step into a function
step # s
# print a variable
print a # p a

# print a variable with format
print /x a # p /x a

# print an array
print a@10 # p a@10
print a[0] # p a[0]

# print address of a variable
print &a # p &a
print &a[0] # p &a[0]

advanced commands

# log the output to a file
set logging file gdb.log
set logging on

# shell command
# use shell command in gdb to run a shell command
shell ls
shell cat test.c

set watchpoint

Watchpoint is used to break when a variable is changed. Can watch a address, a variable, or a expression.

# get the address of a variable
print &a
# set watchpoint
watch *0x7fffffffe0f0

# set watchpoint for a variable
watch a
watch a[0]

# set watchpoint for a expression
watch a + 1

# info watchpoints
info watchpoints