在不必要用到GDB调试或者断点调试的场合,通过使用宏定义包装的信息打印,可以快速定位问题所在。
系统中定义了以下几种宏定义数据
FILE //文件地址
LINE //所在行数
FUNCTION //函数名字
DATE //编译日期
TIME //编译时间
下面上干货,适用于win和linux,在编译时将下面的代码放入debug.h,其他使用文件包含即可
通过 DebugLevel 的宏定义来定义打印级别
#pragma once
#include <iostream>
#include <stdio.h>
#include <string.h>
// Zero_msg 是最低级,当只定义了使用 Zero_msg ,则其他消息不会打印
// 例如在定义了使用 Error_msg 后,所有信息都可以输出
enum Level_d
{
Zero_msg = 0,
Detail_msg,
Info_msg,
Warn_msg,
Error_msg
};
/********************************************************/
// ! 在这里定义打印级别 !
#define DebugLevel Error_msg
/********************************************************/
// windows:
// #define filename(x) strrchr(x,'\\')?strrchr(x,'\\')+1:x
// linux:
#define filename(x) strrchr(x,'/')?strrchr(x,'/')+1:x
#define __output(...) \
{\
printf(__VA_ARGS__);\
}
#define __format_d(__fmt__) "[DETAIL]: <%s/%s()(%d)>-[%s-%s]: " __fmt__ "\n"
#define __format_i(__fmt__) "[INFO]: <%s/%s()(%d)>: " __fmt__ "\n"
#define __format_w(__fmt__) "[WARN]: <%s/%s()(%d)>: " __fmt__ "\n"
#define __format_e(__fmt__) "[ERROR]: <%s/%s()(%d)>: " __fmt__ "\n"
#define DETAIL(__fmt__, ...) \
{\
if(DebugLevel >= Detail_msg){\
__output(__format_d(__fmt__), filename(__FILE__), __FUNCTION__, __LINE__, __DATE__, __TIME__, ##__VA_ARGS__)\
}\
}
#define INFO(__fmt__, ...) \
{\
if(DebugLevel >= Info_msg){\
__output(__format_i(__fmt__), filename(__FILE__), __FUNCTION__, __LINE__, ##__VA_ARGS__)\
}\
}
#define WARN(__fmt__, ...) \
{\
if(DebugLevel >= Warn_msg){\
__output(__format_w(__fmt__), filename(__FILE__), __FUNCTION__, __LINE__, ##__VA_ARGS__)\
}\
}
#define ERROR(__fmt__, ...) \
{\
if(DebugLevel >= Error_msg){\
__output(__format_e(__fmt__), filename(__FILE__), __FUNCTION__, __LINE__, ##__VA_ARGS__)\
}\
}
/********************************************************/
测试样例
#include<iostream>
#include <stdio.h>
#include "debug.h"
int main()
{
DETAIL("dd");
INFO("ii");
WARN("ww");
ERROR("SUB %d", 123);
return 0;
}
输出信息:
[DETAIL]: <main.cpp/main()(78)>-[Apr 10 2019-17:30:32]: dd
[INFO]: <main.cpp/main()(79)>: ii
[WARN]: <main.cpp/main()(80)>: ww
[ERROR]: <main.cpp/main()(81)>: SUB 123