1. 程式人生 > >GDB 除錯工具入門

GDB 除錯工具入門

GDB是GNU開源組織釋出的一個強大的UNIX下的程式除錯工具,通常在伺服器上開發C/C++時,該工具是必不可少的。下面,將通過例子詳細介紹GDB的使用。

1. 源程式 

#include<iostream>
using namespace std;
int c=0;
int& findMax(int &a,int &b)
{
    c= a>=b?a:b;
    return c;
}
int main() {
    int a = 1;
    int b = 2;
    int &c = findMax(a, b);
    cout << c << endl;
    return 0;
}

2. 編譯源程式

     編譯並生成可執行檔案:

      gcc -g -c main.cpp

      g++ -o main main.o

[[email protected] test]$ ls
   main.cpp
[[email protected] test]$ gcc -g -c main.cpp 
[[email protected] test]$ ls
   main.cpp  main.o
[[email protected] test]$ g++ -o main main.o
[[email protected]
test]$ ls main main.cpp main.o

3. 除錯可執行檔案

  • 啟動GDB:  gdb main

        

  • 列出原始碼:l

        

  • 打斷點,檢視斷點資訊:break n;  info break

        

  • 執行程式,在斷點處停止,檢視當前位置:r; where  

        

  • 進入函式內部,單步執行,檢視變數值,完成函式:s; n; p i; finish 

       

  • 繼續執行,退出gdb: c ; q