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>
添加具体的一条命令表示查看命令的使用方式。