用gcc/g++编译程序的时候使用-g或-ggdb选项。

输入

gdb [program name]

开始调试。

r | run program from start
---|---
k | kill current running program
q | quit GDB
info b | get info about current breakpoints
b [source file]:[line number] | set breakpoint at specific line number
b [source file]:[function name] | set breakpoint at specific function entry
en [number] | enable breakpoint [number]
dis [number] | disable breakpoint [number]
d [number] | delete breakpoint [number]
ig [number] [times] | ignore breakpoint [number] for [times] times
cond [number] [expression] | breakpoint [number] takes effect only if
[expression] is true
s | step into (one source line)
n | step over (one source line)
si | step into (one instruction)
ni | step over (one instruction)
c | continue program, after breakpoint
finish | run until current function finishes
p [expression] |

print values of [expression]

[expression] can be [variable name], [function name], [memory address]

disp [expression] |

print values of [expression] each time the program stops

if no [expression] is given, display all

info disp | get info about current displays
en disp [number] | enable display [number]
dis disp [number] | disable display [number]
d disp [number] | delete display [number]
x/[fmt] [expression] |

examine memory at address [expression] using format [fmt]

[fmt] = [number][oxdutfaics][bhwg]

Examples:

x/32xb main

x/32xb 0x8048394

x/w &c (suppose c is of type int)

x/s pc (suppose pc is of type char *)

pt [expression] | print definition of [expression]
bt | print backtrace of all stack frames
f | print current stack frame
f [number] | print stack frame at level [number], 0 is current
l [function name] | list source code near [function name]
l [variable name] | list source code near [variable name]
l | list source code from last call of list (forward)
l - | list source code from last call of list (backward)
info r | get info about current registers
h [command] | get help about [command]
[Enter] | Press Enter repeats the last command

And you may also want this GDB reference card.

Note.

  1. How to list current line?

You can use l. But bare l has memory, i.e., if you run it again, it will display the next several lines. A better solution is f and l *$pc.