zoukankan      html  css  js  c++  java
  • 用gdb调试C程序的简单介绍

    
    
    1.安装gdb 
    引用
    # yum install gbd
    
    
    
    
    这里用的是CentOS或者RedHat的yum来安装,如果是Ubuntu的话就可以用apt-get来安装。 
    
    
    2.编译可调试的C程序 
    要用gdb调试C程序,在编译C程序的时候就要变成成debug的本版,很简单在gcc编译的时候加上“-g”的参数就可以了(trig.c代码请参考前一篇文章http://lveyo.iteye.com/blog/240578) 
    
    
    引用
    # gcc -o trig -g trig.c
    
    
    
    
    3.用gdb调试 
    
    
    引用
    # gdb trig 
    GNU gdb Red Hat Linux (6.5-37.el5_2.2rh) 
    Copyright (C) 2006 Free Software Foundation, Inc. 
    GDB is free software, covered by the GNU General Public License, and you are 
    welcome to change it and/or distribute copies of it under certain conditions. 
    Type "show copying" to see the conditions. 
    There is absolutely no warranty for GDB.  Type "show warranty" for details. 
    This GDB was configured as "i386-redhat-linux-gnu"...Using host libthread_db library "/lib/libthread_db.so.1". 
    
    
    (gdb)
    GDB显示其默认提示符并等待你的命令。首先使用list命令来查看这次调试会话的一部分源代码: 
    
    
    引用
    (gdb) list 
    13              if(!fgets(input, MAX_INPUT, stdin)){ 
    14                      perror("an error occurred.
    "); 
    15              } 
    16              angle = strtod(input, NULL); 
    17 
    18              printf("sin(%e) = %e
    ", angle, sin(angle)); 
    19 
    20              return 0; 
    21      } 
    (gdb)
    
    
    在mian函数入口设置断点,然后用run命令运行程序 
    
    
    引用
    (gdb) break main 
    Breakpoint 1 at 0x80484c5: file trig.c, line 12. 
    (gdb) run 
    Starting program: /tmp/cpro/trig 
    
    
    Breakpoint 1, main () at trig.c:12 
    12              printf("Give me an angle (in radians) ==>"); 
    (gdb)
    
    
    运行到main函数的第一条指令时暂停程序,此时程序暂停在第12行。可以使用list命令来显示main函数中的源代码。每一行代码可以使用step和next命令来单步执行——前者会在执行每一条机器指令之后暂停,后者的执行方式类似,但它不会进入外部函数的内部,而是把函数调用语句当作一条普通语句来执行。 
    
    
    先执行next命令运行printf语句 
    
    
    引用
    (gdb) next 
    13              if(!fgets(input, MAX_INPUT, stdin)){ 
    (gdb) 
    Give me an angle (in radians) ==>3.14 
    16              angle = strtod(input, NULL); 
    (gdb)
    gdb在它调用库函数strtod()将字符串转换为双精度浮点数之前暂停了程序的运行。你可以使用gdb的print命令在调用这个函数前后查看angle变量的值: 
    
    
    引用
    (gdb) print angle 
    $1 = 1.9580527709081361e-305
    
    
    
    
    可以用contuinue命令完成程序运行,知道遇到下一个断点,continue命令简写为c 
    
    
    引用
    (gdb) c 
    Continuing. 
    sin(3.140000e+00) = 1.592653e-03 
    
    
    Program exited normally.
    用q命令推出gdb。


  • 相关阅读:
    (转)STMFD和LDMFD指令个人理解分析
    [原创] linux下的串口调试工具
    详解Makefile 函数的语法与使用 (转)
    sed命令详解(转)
    [转]QT4解决中文乱码(tr的使用 | QTextCodec)
    新型的按键扫描程序,仅三行程序(转)
    VS2010旗舰版不能安装Silverlight4_Tools的解决方案
    ASP.NET MVC3+EF4+Oracle入门实例(六)
    一个ASP.NET文件下载类
    项目管理实践【四】自动编译和发布网站【Using Visual Studio with Source Control System to build and publish website automatically】
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13318365.html
Copyright © 2011-2022 走看看