GDB

1. Compile a Program with Debugging Symbols

使用-g参数编译源文件。

$ gcc -g -Wall -o gdbtest gdbtest.c

2. Tips to Start a Program with GDB

无参数运行:

$ gdb program
(gdb) run (r as shortcut key)

带参数运行:

$ gdb --args program arg1 arg2 ... argN
(gdb) r
$ gdb program
(gdb) r arg1 arg2 ... argN
(gdb) file FILENAME
指定希望debug的程序名
(gdb) run

3. Print Source Code in GDB Console

list命令l as shortcut key

如果不带参数,则列出上次打印位置的后10行代码,list -则列出上次打印位置的前10行代码。

list命令参数指定一个位置打印代码,指定方式:

LINENUM
FILENAME:LINENUM
FUNCTION
FILENAME:FUNCTION

4. Six GDB Tips to Set up Breakpoints

(gdb) break (b as shortcut) X

break命令参数指定方式:

LINENUM
FILENAME:LINENUM
FUNCTION
FILENAME:FUNCTION
+LINENUM 指定一个相对位置为断点
*(memory address)

如果有一个程序并没有使用-g选项编译,那么一些gdb命令无法使用。gdb允许使用内存地址来设置断点等操作:

break *main + 4指定从函数开始处的第4个字节。

(gdb) b <...> if CONDITION

如果CONDITION对应的布尔表达式为真,则设置断点。

Example: break linenum if variable == 1
(gdb) info breakpoints
查看断点信息表

5. Four GDB Commands to Print Debug Info

使用command关键字,可以设置多个命令在抵达断点时自动执行。

(gdb) b CheckValidEmail
Breakpoint 1 at ...
(gdb) command 1
> print prot
> print IPAddr
> end
(gdb)

其中,1是断点号。

(gdb) backtrace (or bt as shortcut)
(gdb) info stack
这两个命令会打印函数调用栈。
(gdb) finish
结束当前函数调用(遇到断点会停?)。
(gdb) frame
打印当前栈帧,包括此时行号。
(gdb) frame FRAMENUM
根据栈帧编号,切换栈帧

6. Six GDB Commands to Trace Variables

(gdb) print VARIABLE/STRUCTURE/*PTR
(gdb) print /x VARIABLE
以十六进制打印
(gdb) print arr
打印数组
(gdb) print arr[96]@5
打印数组中96-100的元素
(gdb) watch VARIABLE
当变量值变化时,程序暂停
(gdb) display VARIABLE
跟踪变量,始终打印变量值
(gdb) info display
(gdb) undisplay DISPLAYID;
(gdb) ptype VARIABLE
查看变量类型

7. Continue, Step-in or Next Operations

(gdb) continue
继续执行直到断点/结束
(gdb) next
执行下一条指令,会越过函数
(gdb) step
执行下一条指令,会进入函数
(gdb) until
结束当前循环

8. Skip/Ingore Breakpoints

(gdb) info breakpoints
列出所有的断点,查看ID
(gdb) ignore 1 1000
将会忽略1号断点1000

9. Remove Breakpoints & Quit from GDB

(gdb) delete BREAKPOINTSID
如果delete不带参数,会删除所有断点
(gdb) q

原文/参考链接

https://www.techbeamers.com/how-to-use-gdb-top-debugging-tips/

https://web.eecs.umich.edu/~sugih/pointers/summary.html

posted @   Pannnn  阅读(48)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
-->
点击右上角即可分享
微信分享提示