1. 程式人生 > >linux環境下除錯程式碼

linux環境下除錯程式碼

//建立檔案test.c
[[email protected] code]$ touch test.c
[[email protected] code]$ ls
test.c
//編輯test.c
[[email protected] code]$ vim test.c

test.c檔案

  1 #include<stdio.h>
  2 
  3 int Sum(int x, int y)
  4 {
  5     return x + y;
  6 }
  7 
  8 int main()
  9 {   
 10     int a = 3;
 11     int b = 4;
 12     int c = Sum(a, b);
 13     printf("Sum = %d\n",c);
 14     return 0;
 15 }

//編譯檔案 
// -o選項  輸入到哪個檔案
//-g選項  必須加,表示為debug版本
[[email protected] code]$ gcc -o test -g test.c
[[email protected] code]$ ls
test  test.c
[[email protected] code]$ gdb
GNU gdb (GDB) Red Hat Enterprise Linux (7.2-92.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/>.
//要除錯的檔案的文字,用關鍵字file
(gdb) file test
Reading symbols from /home/admin/code/test...done.
//顯示程式碼,預設顯示10行
(gdb) l
1	#include<stdio.h>
2	
3	int Sum(int x, int y)
4	{
5		return x + y;
6	}
7	
8	int main()
9	{
10		int a = 3;
(gdb) l
11		int b = 4;
12		int c = Sum(a, b);
13		printf("Sum = %d\n",c);
14		return 0;
15	}
//打斷點,b後面跟行號
gdb) b 12
Breakpoint 1 at 0x80483eb: file test.c, line 12.
(gdb) b 5
Breakpoint 2 at 0x80483c7: file test.c, line 5.
//顯示斷點資訊
(gdb) info b
Num     Type           Disp Enb Address    What
1       breakpoint     keep y   0x080483eb in main at test.c:12
2       breakpoint     keep y   0x080483c7 in Sum at test.c:5
//執行程式碼
(gdb) r
Starting program: /home/admin/code/test 

Breakpoint 1, main () at test.c:12
//提示到達第一個斷點處
12		int c = Sum(a, b);
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.149.el6.i686
//進入函式體
(gdb) s

Breakpoint 2, Sum (x=3, y=4) at test.c:5
5		return x + y;
//單步執行,逐過程,類似VS 的F10
(gdb) n
6	}
//逐語句,類似於VS的F11
(gdb) s
main () at test.c:13
13		printf("Sum = %d\n",c);
//p類似於VS的監視
(gdb) p c
$1 = 7
(gdb) p &c
$2 = (int *) 0xbffff3ac
//顯示特定監視
(gdb) display c
1: c = 7
(gdb) n
Sum = 7
14		return 0;
1: c = 7
//移除特定監視
(gdb) undisplay 1
//結束除錯
gdb) quit
[
[email protected]
code]$
(gdb) info b
Num     Type           Disp Enb Address    What
1       breakpoint     keep y   0x080483eb in main at test.c:12
2       breakpoint     keep y   0x080483c7 in Sum at test.c:5
//刪除斷點
(gdb) d 1
(gdb) info b
Num     Type           Disp Enb Address    What
2       breakpoint     keep y   0x080483c7 in Sum at test.c:5

//調到某一行
gdb) until 14
Sum = 7
main () at test.c:14
14		return 0;
(gdb) 

總結: gdb:除錯程式 file:除錯哪個程式 b:設定斷點 info:顯示斷點 d:刪除斷點 r:執行程式 n:逐過程執行程式碼 s:逐語句執行程式碼 bt:打印出函式呼叫棧(重要)在程式出錯時使用 p:檢視監視資訊 display:顯示監視資訊 undisplay:不顯示監視資訊 finsish:執行到當前函式返回 c:從當前位置開始連續而非單步執行程式 until:執行程式調到某一行 qiut:結束除錯