我想设置一个调试模式,以便只有在打开调试模式时才打印日志语句.例如,如果我有这样的代码
printf("something \n");
.
.
.
perror("something \n");
Run Code Online (Sandbox Code Playgroud)
它只有在调试标志打开时才有效.我不想使用"if"语句.我认为有一种聪明的方法可以使用#define或其他东西来做到这一点.
谢谢提前..
#ifdef _DEBUG // or #ifndef NDEBUG
#define LOG_MSG(...) printf(__VA_ARGS__) // Or simply LOG_MSG(msg) printf(msg)
#else
#define LOG_MSG(...) // Or LOG_MSG(msg)
#endif
Run Code Online (Sandbox Code Playgroud)
在非Debug上构建LOG_MSG将没有任何东西.您可以使用自定义日志记录功能或类方法来调用,而不是使用raw printf定义它.
无需进入特定的库或解决方案,通常人们会创建一个记录器类或函数,以及一个调试标志.调试函数在调用printf或cout之前检查此标志.然后在其余的代码中,您只需调用您的调试函数/方法.
这是一个例子:
class MyDebugger
{
private:
bool m_debug;
public:
MyDebugger();
void setDebug(bool debug);
void debug(const char* message);
};
MyDebugger::MyDebugger()
{
m_debug = false;
}
void MyDebugger::setDebug(bool debug)
{
m_debug = debug;
}
void MyDebugger::debug(const char* message)
{
if(m_debug)
{
cout << message << endl;
}
}
int main(int argc, char** argv)
{
MyDebugger debugger;
debugger.debug("This won't be shown");
debugger.setDebug(true);
debugger.debug("But this will");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当然这是一个非常天真的实现.在实际的记录器类中,有许多级别可以更精细地控制打印多少细节(级别,如错误,警告,信息和调试,以区分消息的重要性).它们也可能允许您登录文件以及stdout.这仍然应该给你一个大致的想法.