天天看點

linux下c語言開發,linux下的C語言開發(gdb調試)

用gdb調試多程序的程式會遇到困難,gdb隻能跟蹤一個程序(預設是跟蹤父程序),而不能同時跟蹤多個程序,但可以設定gdb在fork之後跟蹤父程序還是子程序。以上面的程式為

#include

#include

#include

#define MAXLINE 80

int main(void)

{

int n;

int fd[2];

pid_t pid;

char line[MAXLINE];

if (pipe(fd) < 0)

{

perror("pipe");

exit(1);

}

if ((pid = fork()) < 0)

{

perror("fork");

exit(1);

}

if (pid > 0)

{

close(fd[0]);

write(fd[1], "hello world

", 12);

wait(NULL);

}

else

{

close(fd[1]);

n = read(fd[0], line, MAXLINE);

printf("---------------in-----------");

write(STDOUT_FILENO, line, n);

}

return 0;

}

$ gcc main.c -g

$ gdb a.out

GNU gdb 6.8-debian

Copyright (C) 2008 Free Software Foundation, Inc.

License GPLv3+: GNU GPL version 3 or later

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 "i486-linux-gnu"...

(gdb) l

2#include

3#include

4#include

5

6int main(void)

7{

8pid_t pid;

9char *message;

10int n;

11pid = fork();

(gdb)

12if(pid<0) {

13perror("fork failed");

14exit(1);

15}

16if(pid==0) {

17message = "This is the child

";

18n = 6;

19} else {

20message = "This is the parent

";

21n = 3;

(gdb) b 17

Breakpoint 1 at 0x8048481: file main.c, line 17.

(gdb)set follow-fork-mode child

(gdb) r

Starting program: /home/akaedu/a.out

This is the parent

[Switching to process 30725]

Breakpoint 1, main () at main.c:17

17message = "This is the child

";

(gdb) This is the parent

This is the parent

linux下c語言開發,linux下的C語言開發(gdb調試)
linux下c語言開發,linux下的C語言開發(gdb調試)

---------------------------------------------------------------------

編寫代碼過程中少不了調試。在windows下面,我們有visual studio工具。在Linux下面呢,實際上除了gdb工具之外,你沒有别的選擇。那麼,怎麼用gdb進行調試呢?我們可以一步一步來試試看。

#include 

int iterate(int value)

{

if(1 == value)

return 1;

return iterate(value - 1) + value;

}

int main()

{

printf("%d

", iterate(10));

return 1;

}

既然需要調試,那麼生成的可執行檔案就需要包含調試的資訊,這裡應該怎麼做呢?很簡單,輸入 gcc test.c -g -o test。輸入指令之後,如果沒有編譯和連結方面的錯誤,你就可以看到 可執行檔案test了。

調試的步驟基本如下所示,

(01) 首先,輸入gdb test

(02) 進入到gdb的調試界面之後,輸入list,即可看到test.c源檔案

(03) 設定斷點,輸入 b main

(04) 啟動test程式,輸入run

(05) 程式在main開始的地方設定了斷點,是以程式在printf處斷住

(06) 這時候,可以單步跟蹤。s單步可以進入到函數,而n單步則越過函數

(07) 如果希望從斷點處繼續運作程式,輸入c

(08) 希望程式運作到函數結束,輸入finish

(09) 檢視斷點資訊,輸入 info break

(10) 如果希望檢視堆棧資訊,輸入bt

(11) 希望檢視記憶體,輸入 x/64xh + 記憶體位址

(12) 删除斷點,則輸入delete break + 斷點序号

(13) 希望檢視函數局部變量的數值,可以輸入print + 變量名

(14)希望修改記憶體值,直接輸入 print  + *位址 = 數值

(15) 希望實時列印變量的數值,可以輸入display + 變量名

(16) 檢視函數的彙編代碼,輸入 disassemble + 函數名

(17) 退出調試輸入quit即可