简体   繁体   English

如何在 C++ 中定义常量 _DEBUG

[英]How to define the constant _DEBUG in c++

When I compile and execute thes code, I get...当我编译并执行这些代码时,我得到...

_DEBUG IS NOT defined

Why isn't the constant being shown as defined?为什么常量没有按照定义显示?

using namespace std;

int main() {
  const bool _DEBUG = true;
  #if defined _DEBUG
    std::cout << "_DEBUG IS defined\n";
  #else
    std::cout << "_DEBUG IS NOT defined\n";
  #endif // _DEBUG
}
#define _DEBUG

or或者

#define _DEBUG       1

The second method can be checked with #ifdef _DEBUG or #if _DEBUG .可以使用#ifdef _DEBUG#if _DEBUG检查第二种方法。 Usually _DEBUG is defined in compiler IDE profile.通常_DEBUG在编译器 IDE 配置文件中定义。

#if defined TOKEN only checks if TOKEN is defined as a preprocessor macro , ie with #define TOKEN ... . #if defined TOKEN仅检查是否将TOKEN定义为预处理器宏,即使用#define TOKEN ... Here you have defined it as a (constant) variable, which is not the same thing.在这里,您已将其定义为(常量)变量,这不是一回事。

const bool _DEBUG = true; defines a constant which is known to the compiler and not to the preprocessor.定义一个编译器已知的常量,而不是预处理器。

The following check is executed by the preprocessor before the compiler kicks in, therefore it never sees _DEBUG constant.以下检查在编译器启动之前由预处理器执行,因此它永远不会看到_DEBUG常量。

  #if defined _DEBUG
    std::cout << "_DEBUG IS defined\n";
  #else
    std::cout << "_DEBUG IS NOT defined\n";
  #endif // _DEBUG

To get rid of the issue, you should #define _DEBUG so that the preprocessor knows about the token.为了摆脱这个问题,你应该#define _DEBUG以便预处理器知道令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM