您的当前位置:首页正文

linux GDB 简单用法以及例子

来源:九壹网
       
      首先GDB是类unix系统下一个优秀的调试工具, 当然作为debug代码的工具, 肯定没有IDE来的直观了. 不过, 命令行自然有命令行的有点, 当你无法是使用IDE时, gdb有时会帮上很大的忙.

      下面用1个例子来说明用法吧:

      建立1个目录testgdb2
     1. 编写c文件test.c
#include <stdio.h>
#include <test2.h>

int g_i;
int func(int n){
	g_i=1;	
	int sum = 0, i;
	for (i=1; i<=n; i++){
		sum+=i;
	}
	return sum;
}

int main(){
        g_i=0;	
	int i;
	long result = 0;
	for (i=1; i<=100; i++){
		result += i;
	}

	printf("result[1-100] =%d\n", result);
	printf("result[1-250] =%d\n", func(250));
	printf("result of func2(100) =%d\n", func2(100)); //call func2 in test2.c
}


 可以见到在23行,  call 了 test2.c的函数, 而且引用了头文件 test2.h
 
     2. 编写头文件 ./headfiles/test2.h
#ifndef __TEST2_H_
#define __TEST2_H_
	int func2();
#endif



只声明了1个函数啦
  
   3. 编写c文件test2.c 

#include "test2.h"

int func2(int n){
	int i,sum;
	for (i=1;i<n;i++){
		sum+=i;
	}
	return sum;
}


编写对应函数的内容啦.

    4. 编写Makefile
这里要注意,  gcc 命令默认编译出来的可执行文件是不带调试信息的, 也就是说不能用gdb来调试的.
如果要用gdb来debug程序, 则必须要用-g参数来编译.
Makefile如下图(文件名就是Makefile,放在与test.c同1个目录)

test.o: test.c ./headfiles/test2.h
	gcc -c -g test.c -I ./headfiles/ -o test.o
test2.o: test2.c ./headfiles/test2.h
	gcc -c -g test2.c -I ./headfiles/ -o test2.o
test: test.o test2.o
	gcc test.o test2.o -o test
clean:
	rm -rf *.o 
cleanall:
	rm -rf *.o test





      5. 编写编译脚本, 并执行编译.
    
参照上面Makefile,在同一级目录编写编译脚本mk.mak 如下图: 
  
 
      6.运行 gdb 来启动调试模式
    在当前目录执行gdb, enter

      6.2 gdb 命令 list, 简写l
    
list 命令用来查看对应file命令用查看执行程序的源代码

      例如用list 10命令可以查看test.c 第10行附近的代码
     
 

因篇幅问题不能全部显示,请点此查看更多更全内容

Top