一、前言
平时开发C语言程序时,经常需要调试代码,C语言有一些宏,可以打印出当前的行号、文件名称、日期、时间,对程序的调试起到很大的帮助,可以快速定位问题。特别是开发单片机程序时,使用这些宏打印这些信息或者在LCD上显示程序的编译日期、时间,可以知道这个单片机上的固件是什么时候编译。帮助判断版本。
ANSIC标准定义了可供C语言使用的预定义宏:
__LINE__ : 在源代码中插入当前源代码行号
__FILE__ : 在源代码中插入当前源代码文件名
__DATE__ : 在源代码中插入当前编译日期
__TIME__ : 在源代码中插入当前编译时间
二、打印示例
printf("编译日期与时间: %s,%s\n", __DATE__,__TIME__);
printf("当前所在行号:%d\r\n", __LINE__);
printf("当前源文件名称:%s\r\n", __FILE__);
printf("当前固件编译日期:%s\r\n", __DATE__);
printf("当前固件编译时间:%s\r\n", __TIME__);
三、C语言封装快捷Debug
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#define DEBUG
#ifdef DEBUG
static int DebugPrintf(const char *format, ...)
{
va_list arg_data;
int count;
va_start(arg_data, format); /* 获取可变参数列表 */
fflush(stdout); /* 强制刷新输出缓冲区 */
count = vfprintf(stderr, format, arg_data); /* 将信息输出到标准出错流设备 */
va_end(arg_data); /* 可变参数列表结束 */
return count;
}
#else
static inline int DebugPrintf(const char *format, ...)
{
return 0;
}
#endif
int main()
{
DebugPrintf("编译日期与时间: %s,%s\n", __DATE__,__TIME__);
DebugPrintf("当前所在行号:%d\r\n", __LINE__);
DebugPrintf("当前源文件名称:%s\r\n", __FILE__);
DebugPrintf("当前固件编译日期:%s\r\n", __DATE__);
DebugPrintf("当前固件编译时间:%s\r\n", __TIME__);
return 0;
}
#define DEBUG 开启debug;
//#define DEBUG 关闭debug;
通过DEBUG这个宏来开启是否开启调试信息打印功能,如果程序稳定后,不需要打印调试信息,就可以将DEBUG的定义取消掉即可。