編寫程序時,須要寫不少的調試打印信息,可是在發佈程序的時候,咱們又但願能隱藏這些調試信息,下面提供一種方便快捷的方法,只須要去掉宏定義,在Release版本中將不會再包含調試打印的信息,甚至調試打印的代碼都不須要編譯。網絡
// debuginfo.h #ifndef DEBUGINFO_H_ #define DEBUGINFO_H_ // If we define _DEBUG_INFO_ macro, xprint() will print valid debug info to console. #define __DEBUG_INFO_ #ifdef __DEBUG_INFO_ #define xprint(x, ...) xpod_print(__FILE__, __FUNCTION__, __LINE__, x, ##__VA_ARGS__); #else #define xprint(x, ...) #endif #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> inline void xpod_print(const char* file, const char* func, int line, char *fmt, ...) { va_list argptr; va_start(argptr, fmt); char buffer[1024] = {0}; vsprintf(buffer, fmt, argptr); va_end(argptr); std::cout << ">> " << buffer << " >> File=" << file << ",Func=" << func << ",Line=" << line << std::endl; } #endif /* DEBUGINFO_H_ */ // How to use int main() { int x = 10; int y = 20; xprint("xpod_controller start."); xprint("%d + %d = %d", x, y, x+y); }
宏__DEBUG_INFO控制下面xprint宏的方式,是調用xpod_print()函數仍是留空位。xpod_print實現不定參數打印調試信息,xprint宏帶入文件名稱,函數名稱和行號,在Release版本中,只要註釋掉__DEBUG_INFO宏定義便可,固然也能夠使用編譯器定義的_DEBUG和_RELEASE來自動選擇是否要定義__DEBUG_INFO宏。一樣的,xpod_print()函數除了能夠打印到控制檯以外,也能夠擴展到打印到文件,打印到網絡等,當你使用Release編譯的時候,將會少去不少的代碼。函數