【问题标题】:Removing code in Release mode using macros C++使用宏 C++ 在发布模式下删除代码
【发布时间】:2021-12-11 21:32:08
【问题描述】:

我有一些用于调试的代码,不希望出现在版本中。
我可以使用macros 将它们注释掉吗?
例如:

#include <iostream>

#define p(OwO) std::cout << OwO
#define DEBUG 1    // <---- set this to -1 in release mode

#if DEBUG == 1
#define DBUGstart
#define DBUGend
// ^ is empty when in release mode
#else
#define DBUGstart /*
#define DBUGend    */
/*
IDE(and every other text editor, including Stack overflow) comments the above piece of code,
problem with testing this is my project takes a long
time to build
*/
#endif

int main() {
    DBUGstart;
    p("<--------------DEBUG------------->\n");
    // basically commenting this line in release mode, therefore, removing it
    p("DEBUG 2\n");
    p("DEBUG 3\n");
    DBUGend;
    p("Hewwo World\n");
    return 0x45;
}

对于单行调试,我可以轻松地执行以下操作:

#include <iostream>

#define DEBUG -1  // in release mode
#define p(OwO) std::cout << OwO

#if DEBUG == 1
#define DB(line) line
#else
#define DB(line)
#endif

int main()
{
    DB(p("Debug\n"));
    p("Hewwo World");
    return 0x45;
}

但我想这会有点混乱,多行

我正在使用 MSVC(Visual Studio 2019),如果这不起作用,那么是否有任何其他方法可以实现相同(对于多行,对于单行来说非常简单)?强>

【问题讨论】:

  • 是的,您可以使用宏来(有效地)注释掉代码,例如,如果定义了宏(或 #ifndef/ #endif 如果未定义宏,则允许代码)。您可能希望将NDEBUG 视为宏名称,因为它实际上在标准中用于控制assert() 的使用 - 这是一个经常用于调试目的的函数(注意NDEBUG 的含义是“不调试",因此启用 assert() 的功能(如果未定义)。
  • NDEBUG 不是一个好的选择,因为它是用来控制assert() 宏的,而且头文件是故意不是幂等的。这意味着您可以通过定义或取消定义 NDEBUG 宏并再次包含 &lt;cassert&gt; 来控制宏行为。即使在发布版本中,通常用于一次性诊断版本。

标签: c++ debugging visual-studio-debugging


【解决方案1】:

你让这变得不必要地复杂了。

如果在Release 中没有条件插入C 风格的cmets,只在Debug 中插入代码。 Visual Studio 在 Debug 配置中默认定义了_DEBUG,所以你可以像下面这样使用它:

#include <iostream>

int main() {

    std::cout << "hello there.\n";

#ifdef _DEBUG
    std::cout << "this is a debug build.\n";
#endif

}

【讨论】:

  • FWIW,我不喜欢这个。在 MSVC 中自动调试/发布,但需要为其他编译器手动设置是自找麻烦。
  • 它不是自动的。它只是在项目设置的预处理器部分默认设置为调试配置,但可以删除等。但是如果跨平台是一个问题,最好定义你自己的并在你的跨平台构建工具中设置它。不过,就个人而言,我在这里使用预处理器没有问题;这就像预处理器仍然适用的最后一件事。
【解决方案2】:

您甚至不需要宏。条件编译直接融入语言:

#include <iostream>

constexpr bool gDebug = true;

int foo();

int main() {

    std::cout << "hello there.\n";

    int foo_res = foo();

    if constexpr (gDebug) {
       std::cout << "Foo returned: " << foo_res << "\n";
    }
}

这样做的直接好处是,即使在编译出代码时,它仍然可以检查代码是否有效。

它还干净地处理仅在调试中需要的变量,这些变量在使用基于宏的条件编译时通常会导致仅发布警告消息。

【讨论】:

    猜你喜欢
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    相关资源
    最近更新 更多