C/C++ 之 gdb 调试

来源:互联网 发布:java自学看什么app好些 编辑:程序博客网 时间:2024/05/06 00:49

1.gcc编译器

gcc -c test1.c test2.c -o test
-c 选项将每一个源文件编译成对应的目标文件。如果不设置此项,则目标文件中将只有一个.o文件。
-l 用于指定包含头文件的目录。
-g 该选项可生成能被gdb调试所使用的调试信息。
-o 生成二进制可执行程序


2.gdb调试器

编写代码test.c
#include<stdio.h>int main(){  int i;  long result = 0;  for(i = 0;i<100;i++)    result += i;}

对程序进行编译并生成调试信息
[root@localhost LearnLinux]# gcc -g test.c -o test
使用gdb开始调试
[root@localhost LearnLinux]# gdb testGNU gdb (GDB) Red Hat Enterprise Linux (7.2-50.el6)Copyright (C) 2010 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 "i686-redhat-linux-gnu".For bug reporting instructions, please see:<http://www.gnu.org/software/gdb/bugs/>...Reading symbols from /home/frank/LearnLinux/test...done.(gdb) 

使用l或者list可以查看源码,
list 10  可以查看10行周围源码
list 2,6 查看2到6行源码

使用r或者run可以运行,run后面可以接程序运行需要的参数
例如run 2 “data.txt”

使用b或者break命令设置断点,例如
break 12 在12行断点
break function_my 在函数function_my前打断点
break 12 if i==9 当i值为9时,在第12行打断点
可以使用
(gdb) info locals
i = 5
result = 15
查看局部变量的值

delete breakpoint 1 删除1号断点
enable breakpoint 1 使1号断点有效
disable breakpoint 1 使1号断点无效
clear  清除程序上次停止处的断点
clear 20 删除20行设置的所有断点

用p或者print查看变量值
(gdb) print result
$1 = 136
如果要看全局变量,可以使用文件或者函数加上::的方式,
例如 print 'fun2.c'::x
print 'fun2.c'::sum::x

对程序函数进行调用
print func(12)
print a-b 查看表达式的值
查看连续内存空间的值
print *array@len 查看array指针,长度为len的值
如果是静态数组,可以直接 print + 数组名
p/x i 按照十六进制显示变量i。同理的有 d十进制,u十六进制无符号,o八进制,t二进制,c字符格式,f浮点格式

使用display ,在用户单步跟踪时可以显示变量
例如 display/x i

可以使用set改变变量的值
(gdb) set result=2

跳转执行jump
jump 21 跳转到21行

使用backtrace 打印栈
可以使用shell运行shell命令
shell vim 1.txt


















0 0
原创粉丝点击