標頭檔: 調試開關在標頭檔中
#ifndef __DEBUG_ZWY_H__#define __DEBUG_ZWY_H__#include <stdio.h>#include <stdarg.h>#define _DBG_#define _DBG_LEVEL_INFO_//define _DBG_ to open debug#ifdef _DBG_ #ifdef _DBG_LEVEL_INFO_ /* 如果定義了調試層級為INFO, 那麼同時開啟WARN, ERR開關*/ #ifndef _DBG_LEVEL_WARN_ #define _DBG_LEVEL_WARN_ #endif #ifndef _DBG_LEVEL_ERR_ #define DBG_LEVER_ERR #endif #endif /* 如果定義了調試層級為WARN, 那麼同時開啟ERR開關*/ #ifdef _DBG_LEVEL_WARN_ #ifndef _DBG_LEVEL_ERR_ #define _DBG_LEVEL_ERR_ #endif #endif//_DBG_LEVEL_ERR_ for default #ifndef _DBG_LEVEL_ERR_ #define _DBG_LEVEL_ERR_ #endif#endifvoid __DBG_INFO (const char* file, int line, const char *format, ...);void __DBG_WARN (const char* file, int line, const char *format, ...);void __DBG_ERR (const char* file, int line, const char *format, ...);//redirect print to filesvoid px_dbg_start(FILE *err, FILE *warn, FILE *info);#ifdef _DBG_ #ifdef _DBG_LEVEL_INFO_ #define DBG_INFO(format, args...) __DBG_INFO(__FILE__, __LINE__, format, ##args) #else #define DBG_INFO(format, args...) #endif#else #define DBG_INFO(format, args...) #endif/*************************************************/#ifdef _DBG_ #ifdef _DBG_LEVEL_WARN_ #define DBG_WARN(format, args...) __DBG_WARN(__FILE__, __LINE__, format, ##args) #else #define DBG_WARN(format, args...) #endif#else #define DBG_WARN(format, args...) #endif/**********************************************/#ifdef _DBG_ #ifdef _DBG_LEVEL_ERR_ #define DBG_ERR(format, args...) __DBG_ERR(__FILE__, __LINE__, format, ##args) #else #define DBG_ERR(format, args...) #endif#else #define DBG_ERR(format, args...)#endif#endif
.C檔案
#include "debugtool.h"FILE *g_err_file = NULL;FILE *g_warn_file = NULL;FILE *g_info_file = NULL;/* If you want to redirect the output, use the function eg: If you want to output the error message to a file, you can reassign a value to the err_file*/void px_dbg_start(FILE *err, FILE *warn, FILE *info) { if (err) g_err_file = err; if (err) g_warn_file = warn; if (info) g_info_file = info;}void __DBG_INFO (const char* file, int line, const char *format, ...){ if (g_info_file == NULL) g_info_file = stdout; va_list ap; va_start (ap, format); fprintf (g_info_file, "INFO: File[ %s ], at Line[ %-5d ] : ", file, line); vfprintf (g_info_file, format, ap); fflush(g_info_file); va_end (ap);}void __DBG_WARN (const char* file, int line, const char *format, ...){ if (g_warn_file == NULL) g_warn_file = stderr; va_list ap; va_start (ap, format); fprintf (g_warn_file, "WARN: File[ %s ], at Line[ %-5d ] : ", file, line); vfprintf (g_warn_file, format, ap); fflush(g_warn_file); va_end (ap);}void __DBG_ERR (const char* file, int line, const char *format, ...){ if (g_err_file == NULL) g_err_file = stderr; va_list ap; va_start (ap, format); fprintf (g_err_file, "ERR : File[ %s ], at Line[ %-5d ] : ", file, line); vfprintf (g_err_file, format, ap); fflush(g_err_file); va_end (ap);}
支援3中調試層級,重新導向個層級輸出。
優點:如果未開啟調試開關,調試資訊輸出函數將不會被編譯進目標檔案中(宏替換時替換為空白了),更沒有運行時開銷。
缺點:調試開關在標頭檔中,這樣有點不太方便,不能自訂各模組調試層級。