C語言調試手段:鎖定錯誤的實現方法

來源:互聯網
上載者:User

在項目開發工程中,如果能確定哪個檔案下的 哪個函數下的哪行出錯--即鎖定錯誤,那該多好啊,該文章就是為此而作的。
首先來瞭解一下檔案預設的輸出資訊的函數吧:
檔案資訊函數:
複製代碼 代碼如下:printf("line : %d\n", __LINE__); //當前行數
printf("filename : %s\n", __FILE__); //當前檔案名稱
printf("function : %s\n", __FUNCTION__); //當前函數
printf("time : %s\n", __TIME__); //目前時間
printf ("date : %s\n", __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 <stdio.h>
#include <assert.h>
#define _DEBUG(msg...) printf("[ %s,%s, %d ]=>",__FILE__, __FUNCTION__, __LINE__); printf(msg);printf("\r\n")
#define _ERROR(msg...) printf("[ error: %s, %d]=>", __FILE__, __LINE__);printf(msg); printf("\r\n")
#define _ASSERT(exp) \
do {\
if (!(exp)) {\
printf( "[ %s ] ",#exp);printf("\r\n");\
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 <stdio.h>
//#define DEBUG
int main(void)
{
DBG("xxxx\n");
ERR("xxxx\n");
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)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.