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

C语言调试手段:锁定错误的实现方法

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

C语言调试手段:锁定错误的实现方法

在项目开发工程中,如果能确定哪个文件下的哪个函数下的哪行出错--即锁定错误,那该多好啊,该文章就是为此而作的。
首先来了解一下文件默认的输出信息的函数吧:
文件信息函数:
复制代码 代码如下:
printf("line : %dn", __LINE__);                   //当前行数
printf("filename : %sn", __FILE__);             //当前文件名
printf("function : %sn", __FUNCTION__);  //当前函数
printf("time : %sn", __TIME__);                  //当前时间
printf ("date : %sn",  __DATE__);              //当前日期
输出:
line : 10
filename : test.c
function : main.c
time : 14:13:51
date : Oct 13 2012

理论已足,那就来看看如何锁定错误吧:
一、源文件:
复制代码 代码如下:
[root@localhost for_test]# cat erroutput.c
#include
#include
#define _DEBUG(msg...)    printf("[ %s,%s, %d ]=>",__FILE__, __FUNCTION__, __LINE__);  printf(msg);printf("rn")
#define _ERROR(msg...)    printf("[ error: %s, %d]=>", __FILE__,  __LINE__);printf(msg); printf("rn")
#define _ASSERT(exp)     
                        do {
                                if (!(exp)) {
                                printf( "[ %s ]  ",#exp);printf("rn");
                                assert(exp);
                                }
                        } while (0)
int main(void)
{
        char *p = NULL;
        _DEBUG("DEBUG!");
        _ERROR("ERROR!");
        _ASSERT(NULL != p);
        return 0;
}

二、输出:
复制代码 代码如下:
[root@localhost for_test]# gcc erroutput.c
[root@localhost for_test]# ./a.out
[ erroutput.c,main, 17 ]=>DEBUG!
[ error: erroutput.c, 18]=>ERROR!
[ NULL != p ]
a.out: erroutput.c:19: main: Assertion `((void *)0) != p' failed.
已放弃

TI处理:
复制代码 代码如下:
#ifdef DEBUG
    #define DBG(fmt, args...)  printf("Debug " fmt, ##args)// ##运算符用于把参数连接到一起。预处理程序把出现在##两侧的参数合并成一个符号。
#else
    #define DBG(fmt, args...)
#endif
#define ERR(fmt, args...)  printf("Error " fmt, ##args)
[root@localhost for_test]# cat debug_err.c
#include
//#define DEBUG
int main(void)
{
       DBG("xxxxn");
       ERR("xxxxn");
       return 0;
}
[root@localhost for_test]# ./a.out
Error xxxx

#ifdef __DEBUG
    #define DBG(fmt, args...) fprintf(stderr,"Encode Debug: " fmt, ## args)
#else
    #define DBG(fmt, args...)
#endif
#define ERR(fmt, args...) fprintf(stderr,"Encode Error: " fmt, ## args)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/66556.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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