栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

一次gdb实战 设置断点 单步调试 打印和修改变量值等操作

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

一次gdb实战 设置断点 单步调试 打印和修改变量值等操作

本案例总结了gdb的常用用法,详细规则可参考gdb入门教程

总结在前:

  1. 编译命令gcc -g gdb_test.c -o gdb_test,通过-g选项添加调试信息,否则使用gdb调试时,会报“No symbol table is loaded. Use the "file" command.”错误。
  2. 设置断点:bread(或b) 函数名; bread(或b) -line 行号;例如b main 或 b -line 21。
  3. 开始运行:run,该命令会直接运行到断点位置或直至结束。
  4. 单步执行:next(n),该命令将程序执行一行。
  5. 打印变量:print 变量名,例如print ret。
  6. 修改变量:set 变量名=变量值,例如set ret=1。
  7. 多步执行:continue©,继续运行您的程序 (在停止之后,比如在一个断点之后)。

源代码如下:

#include 
#include 
#include 

struct GDB_TEST
{
    
    int gdb_int;
    char gdb_char[64];
};

static struct GDB_TEST my_dgb_test = 
{
    .gdb_int = 5,
    .gdb_char = "This is my test",
};


void main()
{
    printf("main startn");
    int ret = -1;
    struct GDB_TEST *test = &my_dgb_test;

    if (test->gdb_int == 0) 
    {
        ret = 0;
        printf("now ret and gdb_int is 0n");
    }

    if (test->gdb_int == 1)  
    {
        ret = 1;
        printf("now ret and gdb_int is 1n");
    }
    
    printf("returnn");
	return;
} 

实践:

[10283203@zte.intra@127 c_code]$ gcc -g gdb_test.c -o gdb_test


[10283203@zte.intra@127 c_code]$ gdb gdb_test
GNU gdb (GDB) Red Hat Enterprise Linux 8.2-6.el8
……省略gdb版本信息……
Reading symbols from gdb_test...done.


(gdb) b main 
Breakpoint 1 at 0x40058e: file gdb_test.c, line 21.


(gdb) run
Starting program: /media/vdb1/code_test/c_code/gdb_test 
Missing separate debuginfos, use: yum debuginfo-install glibc-2.28-72.el8_1.1.x86_64

Breakpoint 1, main () at gdb_test.c:21
21          printf("main startn");


(gdb) n
main start
22          int ret = -1;
(gdb) n
23          struct GDB_TEST *test = &my_dgb_test;
(gdb) 
25          if (test->gdb_int == 0)


(gdb) print test->gdb_int
$1 = 5


(gdb) set test->gdb_int=0
(gdb) print test->gdb_int
$2 = 0
(gdb) n
27              ret = 0;
(gdb) n
28              printf("now ret and gdb_int is 0n");
(gdb) n
now ret and gdb_int is 0


31          if (test->gdb_int == 1)
(gdb) print test->gdb_int
$3 = 0
(gdb) set test->gdb_int=1
(gdb) print test->gdb_int
$4 = 1
(gdb) n
33              ret = 1;
(gdb) 
34              printf("now ret and gdb_int is 1n");


(gdb) c
Continuing.
now ret and gdb_int is 1
return
[Inferior 1 (process 1297) exited with code 07]
(gdb) quit
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/869059.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号