如何查看DEBUG条件语句的输出?
How to view the output of DEBUG conditional statement?
我写了一个带有 #ifdef DEBUG
条件语句的代码来在代码块中打印 cout
语句。我的问题是:
- 所以这些条件调试只会在条件期间出现,对吗?
- 如果是,调试代码时如何查看代码块中的输出?
我不确定代码块,但在 visual studio 中,如果您想构建程序的调试或发布版本(或您定义的任何其他版本),您可以 select。这实际上是将标志 DEBUG 设置为 true。而且您不需要手动定义变量。在任何情况下,您都可以为此使用自己的定义。
在调试版本中,#ifdef DEBUG 中的任何内容也将被编译,而在发布版本中,这些代码块将被跳过。要从调试中获取信息,您可以像这样定义宏调试打印。
#define DEBUG_MODE 1 // Or 0 if you dont want to debug
#ifdef DEBUG_MODE
#define Debug( x ) std::cout << x
#else
#define Debug( x )
#endif
然后调用你的Debug( someVariable );如果您构建调试版本,您会在控制台中获得输出,否则什么也不会发生。
如其他 comments/answers 中所述,您可以定义一个宏,例如 DEBUG(message)
以仅在调试版本中打印调试消息。但是,我建议您使用 NDEBUG
而不是 DEBUG
来这样做。 NDEBUG
是一个标准化的预定义宏,如果这是您的意图,它会在发布版本中由编译器自动定义。以这种方式使用它:
// #define NDEBUG ==> not needed, this macro will be predefined by compiler in release build
#ifdef NDEBUG // release build
# define DEBUG(msg)
#else // debug build
# define DEBUG(msg) std::cout << msg
#endif
int main(void)
{
DEBUG("this will be printed to console in debug build only\n");
return 0;
}
我写了一个带有 #ifdef DEBUG
条件语句的代码来在代码块中打印 cout
语句。我的问题是:
- 所以这些条件调试只会在条件期间出现,对吗?
- 如果是,调试代码时如何查看代码块中的输出?
我不确定代码块,但在 visual studio 中,如果您想构建程序的调试或发布版本(或您定义的任何其他版本),您可以 select。这实际上是将标志 DEBUG 设置为 true。而且您不需要手动定义变量。在任何情况下,您都可以为此使用自己的定义。
在调试版本中,#ifdef DEBUG 中的任何内容也将被编译,而在发布版本中,这些代码块将被跳过。要从调试中获取信息,您可以像这样定义宏调试打印。
#define DEBUG_MODE 1 // Or 0 if you dont want to debug
#ifdef DEBUG_MODE
#define Debug( x ) std::cout << x
#else
#define Debug( x )
#endif
然后调用你的Debug( someVariable );如果您构建调试版本,您会在控制台中获得输出,否则什么也不会发生。
如其他 comments/answers 中所述,您可以定义一个宏,例如 DEBUG(message)
以仅在调试版本中打印调试消息。但是,我建议您使用 NDEBUG
而不是 DEBUG
来这样做。 NDEBUG
是一个标准化的预定义宏,如果这是您的意图,它会在发布版本中由编译器自动定义。以这种方式使用它:
// #define NDEBUG ==> not needed, this macro will be predefined by compiler in release build
#ifdef NDEBUG // release build
# define DEBUG(msg)
#else // debug build
# define DEBUG(msg) std::cout << msg
#endif
int main(void)
{
DEBUG("this will be printed to console in debug build only\n");
return 0;
}