记录MacOS gdb 调试方法。

1. 安装gdb

brew search gdb 如果有输出gdb后有对勾,说明gdb已经安装好。

2. gdb 鉴权

参考链接 http://blog.csdn.net/cairo123/article/details/52054280

3. 编写一段 C 程序

以下此段程序的作用是求0-99999这10万个数字中7出现的次数。命名为num_sum.c 当然还有另外利用概率方法的最优解。

  1 #include <stdio.h>
  2 void print_hello()
  3 {
  4     printf("hello1\n");
  5     printf("hello2\n");
  6 }
  7 int main(int argc, char const *argv[]) {
  8   int i, j;
  9   int count = 0;
 10   for (i = 0; i < 100000; i++) {
 11     /* code */
 12     for (j = i; j != 0; j = j / 10) {
 13       /* code */
 14       if (j % 10 == 7) {
 15 //        printf("%d\n", i);
 16         count++;
 17       }
 18     }
 19   }
 20   print_hello();
 21   printf("%d\n", count);
 22   return 0;
 23 }

4. 编译出可执行程序

gcc -g -o num_sum num_sum.c

注意-g参数很重要,生成gdb调试信息

5. 开始调试

gdb num_sum
run ---程序会从头跑到尾,跑完。

如果直接run会提示如下错误

During startup program terminated with signal ?, Unknown signal.

解决办法:

Create a .gdbinit file in your home-direcetory and write "set startup-with-shell off" in it.
File can be created using vim ~/.gdbinit.

总结一句话就是在cd目录下,新建.gdbinit文件,写入set startup-with-shell off信息,重新开始调试。

6. 断点调试

如下命令:

(gdb) b fun_a //对某个函数入口处打断点
(gdb) b filename:lineno  //对某个文件某行打断点
(gdb) i b //查所有断点信息
(gdb) d n //删除某个断点

7. 查看调试信息

(gdb) list //查看当前运行的代码
(gdb) p var //查看某个变量
(gdb) p *var //查看某个指针所指向的内容
(gdb) bt      //查看调用堆栈,core dump时特别有用

8. 单步调试

(gdb) s //单步执行step into 遇到函数会跳入
(gdb) n //单步执行step over,遇到函数不会跳入
(gdb) c //继续运行resume