在C ++中编写调试模式的标准方式 [英] Standard way for writing a debug mode in C++

查看:123
本文介绍了在C ++中编写调试模式的标准方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码中的调试模式中是否有最佳做法或类似的代码?
例如,

Is there a "best practice" or similar for coding in a debug-mode in one's code? For example,

#include <iostream>

int main()
{
    #ifdef MY_DEBUG_DEF
    std::cout << "This is only printed if MY_DEBUG_DEF is defined\n";
    #endif

    return 0;
}

或者这是否被认为是不好的做法,因为代码会变得更麻烦?
我注意到一些库(例如libcurl,这是一个大而着名的库)具有这个功能;如果您使用libcurl定义VERBOSE,您基本上可以调试模式

Or is this considered bad practice because the code gets bit messier? I have noticed some libraries (for example libcurl, which is a large and well-known library) have this feature; if you define VERBOSE with libcurl you get basically a debug mode

谢谢。

推荐答案

更常见的方法是遵循 assert(3 ):包含 #ifndef NDEBUG .... #endif 只对调试有用的代码,并且没有任何重大的副作用。

A more usual way is to follow conventions from assert(3): wrap with #ifndef NDEBUG .... #endifcode which is only useful for debugging, and without any significant side effects.

您甚至可以添加一些调试打印宏,如

You could even add some debug-printing macro like

extern bool wantdebug;
#ifndef NDEBUG
#define OUTDEBUG(Out) do { if (wantdebug) \
   std::cerr << __FILE__ << ":" << __LINE__ \
             << " " << Out << std::endl; \
} while(0)
#else
#define OUTDEBUG(Out) do {}while(0)
#endif

,并使用类似 OUTDEBUG(x =< x)代码中的地方然后,将通过调试器或通过某些程序参数设置 wantdebug 标志。您可能想要发出一个换行符,并刷新 cerr (或 cout 或您自己的调试输出流) code> std :: endl ...-以立即显示调试输出(因此您的程序的未来崩溃仍然会提供明智的调试输出)。

and use something like OUTDEBUG("x=" << x) at appropriate places in your code. Then wantdebug flag would be set thru the debugger, or thru some program arguments. You probably want to emit a newline and flush cerr (or cout, or your own debug output stream) -using std::endl ...- to get the debug output displayed immediately (so a future crash of your program would still give sensible debug outputs).

这篇关于在C ++中编写调试模式的标准方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆