其实我一般调试都是直接打log的,不过gdb调试还是很有用处,尤其是当碰到一些底层错误的需要单步跟踪的时候,比如,想研究一下 Go的runtime是如何实现的的时候。
首先在编译Go程序的时候,要让Go带上编译信息:
$ go build -gcflags=all="-N -l" .
$ gdb test
GNU gdb (Debian 8.2.1-2+b3) 8.2.1
Copyright (C) 2018 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"...
Reading symbols from test...done.
Loading Go Runtime support.
(gdb)
注意这里,它可能会提醒你说,要加一个 .py
到 ~/.gdbinit
里,加!比如我加的就是:
$ cat ~/.gdbinit
set auto-load safe-path /snap/go
来看下常见命令:
- list。列出代码,输入第一次后如果输入回车,那么就会重复以上命令
- break。加断点,一般是list之后,break 行号来加断点
- bt。打印调用链
- info files。打印调试文件信息
- run。运行所要调试的代码
- up 和 down。在frame里跳来跳去
- info args 和 info locals 打印参数和本地变量
- whatis 和 p。打印变量和想要看的值,例如数组啊,函数啊,都可以
- info goroutines。查看所有的goroutine及其ID
- goroutine 命令。对对应的goroutine执行命令。
- q。退出
- help。打印帮助文档
接下来,我们来看看实战例子:
$ go build -gcflags=all="-N -l" .
$ gdb ./test
GNU gdb (Debian 8.2.1-2+b3) 8.2.1
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is