【发布时间】: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宏并再次包含<cassert>来控制宏行为。即使在发布版本中,通常用于一次性诊断版本。
标签: c++ debugging visual-studio-debugging