在不必要用到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