关于使用gdb的一些建议

本文详细解析了Linux环境下程序调试与性能优化的关键技术,包括如何使用gdb进行断点设置、变量查看及多线程程序的调试方法。通过实际案例展示了构建带有调试信息的可执行文件如何增加其大小,并介绍了在调试过程中停止程序执行于函数底部以观察变量状态的方法。此外,文章还强调了利用gdb命令如list和break进行更高效的变量信息获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考:《Linux® Debugging and Performance Tuning: Tips and Techniques》 chapter 3

1. 测试程序

/home/a/j/nomad2:cat gdb_sample2.c 
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void* Thread_function1(void * arg)
{
        unsigned int i=1;
        while(i < 11)
        {
                printf("Child Thread Iteration %d\n",i);
                i++;
                if(i%2)
                        sleep(2);
                else
                        sleep(1);
        }
        return arg;
}
void* Thread_function2(void * arg)
{
        unsigned int i=1;
        while(i < 11)
        {
                printf("Child Thread 2 Iteration %d\n",i);
                i++;
                if(i%2)
                        sleep(2);
                else
                        sleep(1);
        }
        return arg;
}
int main (int argc, char *argv[])
{
        pthread_t thread;
        pthread_t thread2;
        if(pthread_create(&thread,NULL,Thread_function1,NULL))
        {
                return(1);
        }
        if(pthread_create(&thread2,NULL,Thread_function2,NULL))
        {
                return(1);
        }
        unsigned int i = 1;
        while(i < 11)
        {
                printf("Main Loop Iteration %d\n",i);
                i++;
                if(i%2)
                        sleep(1);
                else
                        sleep(2);
        }
        return 0;
}

2. build with debug info increase the executable size.

/home/a/j/nomad2:ls -lrt a.out
-rwxr-xr-x 1 nomad2 member 11341 Oct 1 19:34 a.out
/home/a/j/nomad2:strip --strip-debug a.out
/home/a/j/nomad2:ls -lrt a.out
-rwxr-xr-x 1 nomad2 member 7522 Oct 1 19:42 a.out

3.  关于调试:
1). When debugging, it is often a good practice to stop program execution at the bottom of a function so that a print or multiple displays can be done to see the current values stored in the data the function has altered. 
list       <func name>
break  <line of }>

2). When gdb is used, the print command must

be invoked to display the variable's value. The user can see much more information at one time.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值