编写程序时,须要写不少的调试打印信息,可是在发布程序的时候,咱们又但愿能隐藏这些调试信息,下面提供一种方便快捷的方法,只须要去掉宏定义,在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编译的时候,将会少去不少的代码。函数