【问题标题】:Is there a neat method to output text to debugging pane?有没有一种简洁的方法可以将文本输出到调试窗格?
【发布时间】:2012-05-04 11:26:12
【问题描述】:

我想在调试时显示一些日志消息。一种选择是使用非常丑的

#ifdef DEBUG
    std::cout << "I'm in debug mode!\n";
#endif

JUCE 库中,有一个很好的宏可以将文本输出到调试窗格

DBG("I'm in debug mode!")

juce 解决方案还可以让您做如下理想的事情

int x = 4;
DBG(String("x=") + String(x))

我想知道在 std:: 或 boost:: 中是否存在类似的简洁方法

【问题讨论】:

  • xcode 窗口底部的东西 :)
  • 好吧,不是每个人都使用 xcode,你的问题也没有提到它。 ;)
  • 理想情况下它会是 xcode 或 Visual Studio 底部的 thigy ;)
  • 看,现在我们到了某个地方。但是,如果我在没有 调试窗格的 Emacs 中编码怎么办?我的观点是并不总是有调试窗格。即使有,您写入它的方式也不同(我相信 xcode 只是将标准输出流打印到调试窗格,但 Visual Studio 要求您使用 DebugOutputString() 函数。所以制作一个通用的解决方案是几乎不可能。:)
  • JUCE 中的那个在两个平台上都能很好地工作

标签: c++ debugging macros console


【解决方案1】:

为什么不自己写:

#ifdef DEBUG
#define DBG(x) std::cout << x;
#else
#define DBG(x)
#endif

对于命名空间

namespace DBG
{
inline void DBG(const char* x)
{
#ifdef DEBUG
    std::cout << x;
#endif
}
}

【讨论】:

  • 有没有办法把它放到命名空间中?
  • @learnvst:宏不适合命名空间,但宏版本允许这样做:DBG("first: " &lt;&lt; first &lt;&lt; ", second: " &lt;&lt; second);
  • @stefaanv 我知道行为不一样,但实际上没有其他方法可以将它放在命名空间中。
  • 我现在有了我想要的解决方案。我使用上面的第二个示例,但将std::string 作为函数输入。如果需要,我可以在使用int x = 4; utils::DBG("abc" + boost::lexical_cast&lt;std::string&gt;x) 时使用boost::lexical_cast 添加数值。除非有人提出更简洁的方法,否则我会继续这样做。
  • @Luchian:我同意。我刚刚向 OP 展示了他仍然必须在两者之间做出选择,显然,他做到了。 (虽然,我不想在我的日志中看到 lexical_cast)
【解决方案2】:

如果你想要类似 printf 的东西,你应该使用其他宏:

void DebugPrintLn(const char* format, ...);
inline void Nothing(...) {}

#ifdef DEBUG
#define DBG DebugPrintLn
#else
#define DBG Nothing // Or __noop on Visual C++
#endif

使用Nothing 是可移植的,但仍会计算参数(__noop 保证任何参数都将计算,特定于 VC++)。如果你可以使用宏变量参数更好(在 GCC 和最新的 VC++ 上都可用):你甚至可以以可移植的方式跳过任何参数计算:

#ifdef DEBUG
#define DBG(...) DebugPrintLn(__VAR_ARGS__)
#else
#define DBG(...) ((void)0)
#endif

无论如何,你用同样的方式:

DBG("Lucky day: %s %i", "Friday", 13);

【讨论】:

    【解决方案3】:

    我还编写了自己的可移植 TRACE 宏。我在这里分享:

    #ifdef ENABLE_TRACE
    #  ifdef _MSC_VER
    #    include <windows.h>
    #    include <sstream>
    #    define TRACE(x)                           \
         do {  std::stringstream s;  s << (x);     \
               OutputDebugString(s.str().c_str()); \
            } while(0)
    #  else
    #    include <iostream>
    #    define TRACE(x)  std::clog << (x)
    #  endif        // or std::cerr << (x) << std::flush
    #else
    #  define TRACE(x)
    #endif
    

    示例:

    #define ENABLE_TRACE  //can depend on _DEBUG or NDEBUG macros
    #include "my_above_trace_header.h"
    
    int main (void)
    {
       int     v1 = 123;
       double  v2 = 456.789;
       TRACE ("main() v1="<< v1 <<" v2="<< v2 <<'\n');
    }
    

    欢迎任何改进/建议/贡献;-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-30
      • 2012-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      相关资源
      最近更新 更多