debugging 如何重载printf或cout

xfb7svmp  于 2023-06-30  发布在  其他
关注(0)|答案(3)|浏览(142)

我在程序中使用cout语句用于调试目的。我想做一个像它一样工作的函数,或者像printf一样工作,但对全局变量敏感。如果这个全局变量为true,那么它将打印到屏幕。如果它是假的,那么它不会打印任何东西。现在有这样的功能吗?如果不是,那又如何能做到呢?

5uzkadbs

5uzkadbs1#

就像这样:

int myPrintf(const char* format, ...) 
{
  if (globalCheck == 0)
    return 0
  va_list vl;
  va_start(vl, format);
  auto ret = vprintf(format, vl);
  va_end(vl);
  return ret;
}

va_startva_end接受...中的参数,并将它们封装在va_list中。有了这个va_list,你可以然后vprintf,这是一个变种的printf专为这一需要。
旁注-通常使用全局变量是不好的做法。更好的做法是将其封装在一个类中,如下所示-

class ConditionalPrinter {
public:
  ConditionalPrinter() : m_enable(true) {}
  void setOut(bool enable) { m_enable = enable; }
  int myPrintf(const char* format, ...);
private:
  bool m_enable;
}

然后检查m_enable而不是全局变量。this的用法如下:

ConditionalPrinter p;
p.myPrintf("hello %d", 1);   // printed
p.setOut(false);
p.myPrintf("hello2 %d", 1);  // not printed

....

b91juud3

b91juud32#

不要自己写。做正确的事情比你想象的要难得多。当你需要线程和效率时,就更难了。使用现有的日志库之一,如:

z18hc3ub

z18hc3ub3#

正如其他人所说,有几个很好的日志框架可用。然而,如果你想自己滚动,首先要注意的是cout不是一个函数,它是一个流。函数为operator<<。你可以做的事情如下:

/* trace.h */
extern ostream debug;

void trace_init();
void trace_done();

/* trace.cpp */
#include "trace.h"
ostream debug(cout.rdbuf());
static ofstream null;

void trace_init()
{
    null.open("/dev/null");
    if(output_is_disabled) {  // put whatever your condition is here
        debug.rdbuf(null.rdbuf());
    }
}

void trace_done()
{
    null.close();
}

如果您在没有/dev/null的平台上,则可能需要进行一些调整。它能让你写出

debug << "here's some output << endl;

如果您启用了输出,它将写入cout。如果没有,它将写入/dev/null,您将看不到任何内容。
就此而言,您可以将cout的rdbuf设置为不会看到输出的位置,但我认为这是一个非常糟糕的主意。创建新的流可以让您更灵活地控制输出。

相关问题