一、测试用程序
#include<stdio.h>
int main(){
int a = 1;
int b = 2;
int c = a + b;
printf("c is %d",c);
}
二、生成可调试程序文件
要想调试c/c++程序,需要在编译程序时,向生成的可执行文件中添加调试信息,编译时使用如下命令:
gcc -g test.c -o test
三、启动调试
使用如下命令进入调试模式:
gdb test
打印信息如下:
ZQ-Think-PC-MacBook-Pro:c+plus zq$ gdb test
GNU gdb (GDB) 7.9.1
Copyright (C) 2015 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-apple-darwin14.4.0".
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...Reading symbols from /Users/zq/Documents/c+plus/test.dSYM/Contents/Resources/DWARF/test...done.
done.
(gdb)
四、列出可执行文件源码
在调试模式下执行如下命令,列出调试的可执行文件源码:
l(list的首字母)
打印信息如下:
(gdb) l
1 #include<stdio.h>
2 int main(){
3 int a = 1;
4 int b = 2;
5 int c = a + b;
6 printf("c is %d",c);
7 }
五、设置断点
列出源码之后,就可准确的设置断点了,使用如下命令:
b + 行号
加断点还有如下方式:
b + func(函数名)在当前文件的函数入口处暂停
b + filename:function 在指定文件的函数入口处暂停
b + filename:linenum 在指定文件的行号处暂停清除断点
使用clear
命令,使用方式和b
方式对应。
比clear
命令更合适的是断点暂时失效的命令为disable
,使用方式和b
对应。查看所有断点
使用命令info + b
六、运行程序
执行如下命令即可运行程序,开始调试:
r (run的首字母)
七、启动图形化调试模式
参考博文:图形化GDB调试(TUI模式)
八、调试快捷键
n
执行单条语句
p
打印运行时变量的值
s
进入函数,类似F5
bt
查看当前函数调用的堆栈信息