C language debugging means: lock error implementation method
- 2020-04-02 00:45:47
- OfStack
In the project development project, if can determine which file under
Which line under which function went wrong -- that is, the locking error
That would be nice. That's what this article is about.
First, let's take a look at the default output function of the file:
File information function:
Now that the theory is complete, let's take a look at how to lock errors:
I. source file:
Ii. Output:
TI:
First, let's take a look at the default output function of the file:
File information function:
printf("line : %dn", __LINE__); //The current line number
printf("filename : %sn", __FILE__); //Current file name
printf("function : %sn", __FUNCTION__); //The current function
printf("time : %sn", __TIME__); //The current time
printf ("date : %sn", __DATE__); //The current date
Output:
line : 10
filename : test.c
function : main.c
time : 14:13:51
date : Oct 13 2012
Now that the theory is complete, let's take a look at how to lock errors:
I. source file:
[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("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;
}
Ii. Output:
[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.
Have to give up
TI:
#ifdef DEBUG
#define DBG(fmt, args...) printf("Debug " fmt, ##args)//The ## operator is used to connect parameters together. The preprocessor merges the arguments that appear on either side of ## into a symbol.
#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("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)