有没有办法在程序内部使用std::cout定义/取消定义调试消息?
我知道有像#define,#ifndef这样的东西,但我在想,有没有一种更简洁的方法让变量说:
# debug ON
这将打印我所有的调试数据(使用std::cout)。因此,我们将有这样的代码用于调试:
#ifndef DEBUG
// do something useful
#endif
当你写了上百段调试代码时,我发现上面的代码很麻烦。
谢谢!
卡洛
发布于 2010-07-30 21:38:52
有些日志库非常重,除非您有复杂的日志需求。这是我刚刚拼凑起来的东西。需要一些测试,但可能会满足您的要求:
#include <cstdio>
#include <cstdarg>
class CLog
{
public:
enum { All=0, Debug, Info, Warning, Error, Fatal, None };
static void Write(int nLevel, const char *szFormat, ...);
static void SetLevel(int nLevel);
protected:
static void CheckInit();
static void Init();
private:
CLog();
static bool m_bInitialised;
static int m_nLevel;
};
bool CLog::m_bInitialised;
int CLog::m_nLevel;
void CLog::Write(int nLevel, const char *szFormat, ...)
{
CheckInit();
if (nLevel >= m_nLevel)
{
va_list args;
va_start(args, szFormat);
vprintf(szFormat, args);
va_end(args);
}
}
void CLog::SetLevel(int nLevel)
{
m_nLevel = nLevel;
m_bInitialised = true;
}
void CLog::CheckInit()
{
if (!m_bInitialised)
{
Init();
}
}
void CLog::Init()
{
int nDfltLevel(CLog::All);
// Retrieve your level from an environment variable,
// registry entry or wherecer
SetLevel(nDfltLevel);
}
int main()
{
CLog::Write(CLog::Debug, "testing 1 2 3");
return 0;
}
发布于 2010-07-30 20:54:28
#ifdef DEBUG
#define DEBUG_MSG(str) do { std::cout << str << std::endl; } while( false )
#else
#define DEBUG_MSG(str) do { } while ( false )
#endif
int main()
{
DEBUG_MSG("Hello" << ' ' << "World!" << 1 );
return 0;
}
发布于 2017-07-21 13:51:24
另一个简单的解决方案是在调试模式下打开对cout
的std::ostream
引用,在非调试模式下打开/dev/null
引用,如下所示:
在debug.h中:
extern std::ostream &dout;
在debug.c中
#ifdef DEBUG
std::ostream &dout = cout;
#else
std::ofstream dev_null("/dev/null");
std::ostream &dout = dev_null;
#endif
然后:
dout << "This is a debugging message";
当然,这只适用于/dev/null
指向空设备的任何系统。因为这里的dout
引用是全局的,所以它与cout
非常相似。通过这种方式,您可以将同一个流指向多个输出流,例如指向日志文件,这取决于调试标志的值等。
https://stackoverflow.com/questions/3371540
复制相似问题