GDB 调试

hello word

准备一份c++代码:

#include <iostream>

int main()
{
    int counter = 0;
    for(int loopIdx = 0; loopIdx < 6; loopIdx++){
        counter++;
        std::cout << "counter is " << counter << std::endl;
    }
    std::cout << "finish!" << std::endl;
    return 0;
}

在使用gcc编译时,需要加上生成调试信息的参数-g

g++ hello.cpp -o hello -g

编译之后生成带有dbg信息的可执行文件hello

开始调试

启动调试

gdb hello -q

加参数-q是为了简化启动时输出的信息,也可以使用--silent--quiet

xx@xxxxx:~/gdb/code$ gdb hello -q #启动gdb
Reading symbols from hello...
(gdb) b 7                         #在第7行放断点
Breakpoint 1 at 0x11e9: file hello.cpp, line 7.
(gdb) r                           #run
Starting program: /home/jk/gdb/code/hello 

Breakpoint 1, main () at hello.cpp:7
7               counter++;        #停在断点处
(gdb) p counter                   #查看变量值
$1 = 0
(gdb) c                           #继续运行
Continuing.
counter is 1

Breakpoint 1, main () at hello.cpp:7
7               counter++;
(gdb) c
Continuing.
counter is 2

Breakpoint 1, main () at hello.cpp:7
7               counter++;
(gdb) c
Continuing.
counter is 3

Breakpoint 1, main () at hello.cpp:7
7               counter++;
(gdb) c
Continuing.
counter is 4

Breakpoint 1, main () at hello.cpp:7
7               counter++;
(gdb) c
Continuing.
counter is 5

Breakpoint 1, main () at hello.cpp:7
7               counter++;
(gdb) c
Continuing.
counter is 6
finish!
[Inferior 1 (process 20946) exited normally]
(gdb) q                           #退出

GDB常用的调试指令如下表

调试指令作用
(gdb) break xxx
(gdb) b xxx
在源代码指定的某一行设置断点,其中 xxx 用于指定具体打断点的位置。
(gdb) run
(gdb) r
执行被调试的程序,其会自动在第一个断点处暂停执行。
(gdb) continue
(gdb) c
当程序在某一断点处停止运行后,使用该指令可以继续执行,直至遇到下一个断点或者程序结束。
(gdb) next
(gdb) n
令程序一行代码一行代码的执行。
(gdb) print xxx
(gdb) p xxx
打印指定变量的值,其中 xxx 指的就是某一变量名。
(gdb) list
(gdb) l
显示源程序代码的内容,包括各行代码所在的行号。
(gdb) quit
(gdb) q
终止调试。

表中的所有命令都可以通过(gdb)help来查询。

查看具体某个类型中的命令

命令总体被划分成了12种,查看各个种类种的命令使用方法:

(gdb) help <class>

其中 表示help命令显示的GDB中的命令的种类,如:

(gdb) help breakpoints
Making program stop at certain points.
 
List of commands:
 
awatch -- Set a watchpoint for an expression
break -- Set breakpoint at specified location
break-range -- Set a breakpoint for an address range
catch -- Set catchpoints to catch events
catch assert -- Catch failed Ada assertions
catch catch -- Catch an exception
……

列举的只是breakpoints这个种类中得一小部分,关于 breakpoints 相关的命令非常多。

命令的具体使用方式

具体某条命令的使用方法,也可以使用help命令,使用方法如下:

(gdb) help <command>

<command>表示的是具体的一条命令,如:

(gdb) help break
Set breakpoint at specified location.
break [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]

help会显示出这条命令的含义以及使用方式。

help小结

help单独使用是查看命令的种类。
help <class>添加命令的种类表示使用这条命令查看各个种类中具体命令选项。
help <command>添加具体的一条命令表示查看命令的使用方式。

GDB 简介
GDB 安装
GDB 调试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值