Linux-Ubuntu下gdb调试笔记

来源:互联网 发布:淘宝皇冠号能卖多少钱 编辑:程序博客网 时间:2024/04/29 12:41

想在Ubuntu下模仿cp指令编写一个类似的较为简单的文件拷贝指令。

基本地,该程序需要接受两个参数:源文件/文件夹以及目标文件夹——cp src dst。

苦于接触Linux不久,对于这类有一点代码量的程序的调试就犯难,各种搜索终于学到了点技巧。

开始遇到的麻烦就是对于使用

sudo gcc mycp.c -o mycp

指令生成的目标文件不能调试,应该添加-g参数,在目标文件中加入调试信息。

gcc -g -o mycp mycp.c(似乎这种写法也可:sudo gcc -g mycp.c -o mycp)

之后的麻烦就是比如以下代码,不会加入参数,导致每次都输出Argument error.

int main(int argc, char *argv[])  {      if (argc < 3)      {          printf("Argument error\n");             }     return 0; }

郁闷之余终于找到了调试方法。

使用gdb指令进行调试,命令行最左端出现(gdb)字符则表示已经处于调试状态,此时打入不同的调试指令即可(和VS之类的集成环境不能比,可能习惯就好吧)。

gregocean@ubuntu:/mnt/hgfs$ sudo gdb mycp

GNU gdb (GDB) 7.2-ubuntu
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-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /mnt/hgfs/mycp...done.

(gdb) set args /mnt/hgfs /mnt//使用set args加入参数

(gdb) b 3 //在第三行加入断点,也可使用 /mnt/hgfs /mnt 直接在启动调试的同时加入参数,这样就不需set args了。
Breakpoint 1 at 0x8048c5b: file mycp.c, line 128.
(gdb) r //开始运行调试(run)
Starting program: /mnt/hgfs/mycp /mnt/hgfs /mnt

Breakpoint 1, main (argc=3, argv=0xbffff824) at mycp.c:3
3    if (argc != 3)  
(gdb) p argc //使用p查看当前行某变量值
$1 = 3 //可以看到argc值为3,说明参数传入了。之后使用n单步调试(逐过程),或者s(逐语句,进入函数之类)。

gdb的参数详解

原创粉丝点击