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