当别名定义为“const int alias = variable”而不是#define时使用ifndef时重新定义错误

the*_*ive 0 c++ c-preprocessor ifndef

我定义const UInt8 HE = he;里面namespace Portsports.h。然后我将它包含在ports_logic.h和 中ports_logic.h,我在里面有以下代码namespace Ports

#ifndef HP
const UInt8 HP = hp;
#endif
Run Code Online (Sandbox Code Playgroud)

但是在编译过程中,它给了我以下错误。

在此处输入图片说明

有什么替代方法ifndef可以帮助我检查是否const int HP已经定义?

谢谢。

Ste*_*ner 5

简而言之,const UInt8 HP = hp;不会引入#ifndef HP可能对其做出反应的预处理器标识符。

通过#define预处理器指令定义的标识符和变量的定义是两件不同的事情。预处理器指令在编译器分析代码并识别变量、函数等之前展开。因此,变量的定义不能#define作为预处理器的标识符,因为此时预处理已经发生。

你可以通过写来克服这个...

#ifndef HP_VAR
  #define HP_VAR
  const UInt8 HP = hp;
#endif
Run Code Online (Sandbox Code Playgroud)