GDB是GNU下的Linux端程序调试工具

gdb位置:

1
2
issak@ubuntu:~$ which gdb
/usr/bin/gdb

编译

1
2
3
4
5
# 关闭内联优化,方便调试
$ go build -gcflags "-N -l" demo.go

# 发布版本删除调试符号
go build -ldflags “-s -w”

使用gdb命令启动调试界面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
issak@ubuntu:~/go/src/hello$ gdb demo
GNU gdb (Ubuntu 9.2-0ubuntu1~20.04.1) 9.2
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".
Type "apropos word" to search for commands related to "word"...
--Type <RET> for more, q to quit, c to continue without paging--
Reading symbols from demo...
warning: File "/usr/local/go/src/runtime/runtime-gdb.py" auto-loading has been declined by your `auto-load safe-path' set to "$debugdir:$datadir/auto-load".
To enable execution of this file add
add-auto-load-safe-path /usr/local/go/src/runtime/runtime-gdb.py
line to your configuration file "/home/issak/.gdbinit".
To completely disable this security protection add
set auto-load safe-path /
line to your configuration file "/home/issak/.gdbinit".
For more information about this security protection see the
"Auto-loading safe path" section in the GDB manual. E.g., run from the shell:
info "(gdb)Auto-loading safe path"
(gdb)

调试命令

  • r:run,执行程序

  • n:next,下一步,不进入函数

  • s:step,下一步,会进入函数

  • b:breakponit,设置断点

  • l:list,查看源码

  • c:continue,继续执行到下一断点

  • bt:backtrace,查看当前调用栈

  • p:print,打印查看变量

  • q:quit,退出 GDB

  • whatis:查看对象类型

  • info breakpoints:查看所有的断点

  • info locals:查看局部变量

  • info args:查看函数的参数值及要返回的变量值

  • info frame:堆栈帧信息

  • info goroutines:查看 goroutines 信息。在使用前 ,需要注意先执行 source /usr/local/go/src/runtime/runtime-gdb.py

  • goroutine 1 bt:查看指定序号的 goroutine 调用堆栈

  • 回车:重复执行上一次操作

具体还是要多实践,多操作才能熟练掌握gdb的使用