linux gdb

安装gdb

sudo apt-get install gdb

编译test

  1. 在编译指令里记得加上 -g 参数,这个会使得编译出来的程序可以使用gdb进行调试
    $ g++ -g test.cpp -o test
  2. gdb载入可执行文件,这里有两个方法

直接运行 gdb test

或:

gdb + file test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$ gdb
GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.h
tml>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copyin
g"
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".
(gdb) gdb tes
Undefined command: "gdb". Try "help".
(gdb) gdb file test
Undefined command: "gdb". Try "help".
(gdb) file test
Reading symbols from test...done.
(gdb)

基本命令:

  • l : 输出代码,输出当前上下各10行的代码
  • b 行数 : 在那一行上设置断点
  • r : 运行整个程序,直至遇到断点
  • s : 单步继续执行(进入函数)
  • n : 单步继续进行 (不进入函数,直接把子函数一并运行完)
  • q : 退出gdb
  • d num : num为断点编号, 删除该断点
  • c : continue , 继续运行直至下一个断点
  • p exp : 查看变量exp的内容
  • k :kill掉当前运行的程序(然后再用r来重新调试)

breakpoint进阶

  • b 行数 if i > 9 :增加条件, 当 i > 9的时候,程序运行到num行会停下来。
  • info break : 查看断点信息,包括所有断点号,禁用情况等
  • 删除breakpoint:
    • clear 行数 :删除该行上的所以断点
    • d :删除所有的断点
    • d 1-6 :删除编号是1~6的断点
  • 禁用断点相关:
    • disable num :禁用某个断点
    • disable :全部禁用
    • enable num :启用某个断点
    • enable :全部启用
  • 在其他文件里面设置断点
    • b 文件名 : 函数名/行数 :for example:
      (gdb) b AgendaService.cpp : AgendaService::startAgenda()

设置观察点 (数据断点):

watch 变量/表达式

  • 当观察点的内容有变化的时候,即立刻停止
  • 用delete来删除观察点
  • info watchpoints 来查看所有观察点的信息

p 命令

  • p 后的变量必须是全局变量或者是当前可见的局部变量,如果两者同名,则优先查看局部变

  • p 还可以显示其他数据结构,比如说,在调试agenda的时候,可以直接 p startdate ,这
    样就可以直接看startdate这个Date类里面的全部内容了

ptype命令

通过 ptype var 可以查看var的数据类型

bt命令

bt 查看程序crash堆栈信息

当程序被停住了,你需要做的第一件事就是查看程序是在哪里住的。当你的程序调用了一个函数,函数的地址,函数参数,数内的局部变量都会被压入“栈”(Stack)中。你可以用GDB令来查看当前的栈中的信息。

1
2
3
4
5
(gdb) bt
#0 func (n=250) at tst.c:6
#1 0x08048524 in
main (argc=1, argv=0xbffff674) at tst.c:30
#2 0x40040Arrayed in __libc_start_main () from /lib/libc.so.6
  1. 程序崩溃的时候,这个时候查看最近的堆栈消息,可以非常快地查看到是在哪里出错的。
  2. 当你确认了一个函数有bug,这个函数被其他很多函数调用,这个时候,程序在这个函数停
    下来的时候使用bt命令,就可以知道是哪个函数调用了有问题的函数。

display命令

display + var 来使用自动显示var的值

set命令

set tol=100 这样可以在程序运行时把tol设置为100

Donate? comment?