这里,介绍一个头文件,客制化了日志,方便我们调试。
在编写程序的时候,添加上这个头文件,就可以了。代码如下:
log.h:
#ifndef _LOG_H_ #define _LOG_H_ #include<stdio.h> #define DEBUG_EN (1u) #if (DEBUG_EN) #define DEBUG_MAX_SIZE 512 unsigned char szBuf[DEBUG_MAX_SIZE]; #define DEBUG_INFO( format, ... ) do{\ unsigned short unLen = 0;\ unLen += snprintf(szBuf+unLen,DEBUG_MAX_SIZE, "[INFO][%s][@%s][#%d]:",__FILE__,__FUNCTION__,__LINE__);\ unLen += snprintf(szBuf+unLen,DEBUG_MAX_SIZE-unLen, format, ## __VA_ARGS__ );\ printf("%s",szBuf);\ }while(0) #define DEBUG_WARN( format, ... ) do{\ unsigned short unLen = 0;\ unLen += snprintf(szBuf+unLen,DEBUG_MAX_SIZE, "[WARN][%s][@%s][#%d]:",__FILE__,__FUNCTION__,__LINE__);\ unLen += snprintf(szBuf+unLen,DEBUG_MAX_SIZE-unLen, format, ## __VA_ARGS__ );\ printf("%s",szBuf);\ }while(0) #define DEBUG_ERR( format, ... ) do{\ unsigned short unLen = 0;\ unLen += snprintf(szBuf+unLen,DEBUG_MAX_SIZE, "[ERR][%s][@%s][#%d]:",__FILE__,__FUNCTION__,__LINE__);\ unLen += snprintf(szBuf+unLen,DEBUG_MAX_SIZE-unLen, format, ## __VA_ARGS__ );\ printf("%s",szBuf);\ }while(0) #else #define DEBUG_INFO(...) #define DEBUG_WARN(...) #define DEBUG_ERR(...) #endif //DEBUG_EN #endif //_LOG_H_
使用:main.c
#include<stdio.h> #include"log.h" int main(){ int a = 2; printf("this is a test %d\n",a); DEBUG_INFO("this is a test %d\n",a); DEBUG_WARN("this is a test %d\n",a); DEBUG_ERR("this is a test %d\n",a); return 0; }
编译:gcc -o test main.c
结果:
this is a test 2 [INFO][main.c][@main][#10]:this is a test 2 [WARN][main.c][@main][#11]:this is a test 2 [ERR][main.c][@main][#12]:this is a test 2
如果,我们不需要日志,可以将 #define DEBUG_EN (1u) 注释即可。
标签:__,unLen,程序,test,添加,DEBUG,日志,szBuf,define From: https://www.cnblogs.com/haoran123/p/17361988.html