---
title: "linux下编译C程序(二)——gdb简单调试"
author: "lveyo"
date: "2008-09-26T12:38:02Z"
tags: ["C", "C#", "C++", "Linux", "RedHat"]
categories: ["编程语言"]
slug: "linux-c-gdb"
draft: false
lastmod: "2008-09-26T12:38:02Z"
id: 247013
url: "https://lveyo.iteye.com/blog/247013"
---

用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.\n");
> 15              }
> 16              angle = strtod(input, NULL);
> 17
> 18              printf("sin(%e) = %e\n", 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。