简体   繁体   English

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

[英]Redefinition error when using ifndef when alias is defined like “const int alias = variable” instead of #define

I defined const UInt8 HE = he;我定义const UInt8 HE = he; inside namespace Ports in ports.h .ports.h中的namespace Ports内。 Then I included it in ports_logic.h and in ports_logic.h , I have the following code inside namespace Ports然后我将它包含在ports_logic.hports_logic.h中,我在namespace Ports中有以下代码

#ifndef HP
const UInt8 HP = hp;
#endif

However during compilation, it gives me the following error.但是在编译期间,它给了我以下错误。

在此处输入图像描述

What is the alternative to ifndef that can help me check if the const int HP has already been defined? ifndef的替代方法可以帮助我检查是否已经定义了const int HP

Thanks.谢谢。

Briefly, const UInt8 HP = hp;简而言之, const UInt8 HP = hp; does not introduce a pre-processor identifier on which #ifndef HP could ever react on.没有引入#ifndef HP可以对其作出反应的预处理器标识符。

Identifiers defined through #define preprocessor directive and the definition of variables are two different things.通过#define预处理器指令定义的标识符和变量的定义是两个不同的东西。 Preprocessor directives are expanded before the compiler analyses the code and identifies variables, functions, etc. Therefore, the definition of a variable cannot #define an identifier for the preprocessor, since preprocessing has already taken place at this moment.预处理器指令在编译器分析代码并识别变量、函数等之前被扩展。因此,变量的定义不能#define预处理器的标识符,因为此时已经进行了预处理。

You could overcome this by writing...你可以通过写作来克服这个...

#ifndef HP_VAR
  #define HP_VAR
  const UInt8 HP = hp;
#endif

You're confusing the preprocessor and the compiler.您混淆了预处理器和编译器。 Declaring a C++ variable does not define anything in the preprocessor.声明 C++ 变量不会在预处理器中定义任何内容。 Let's look line-by-line:让我们逐行看:

#ifndef HP

This is handled by the preprocessor.这由预处理器处理。 The only way for this to fail is by #define HP or similar.失败的唯一方法是通过#define HP或类似方法。 The C++ compiler never sees this line. C++ 编译器永远不会看到这一行。

const UInt8 HP = hp;

This is handled by the C++ compiler after the preprocessor has done its thing.这是由 C++ 编译器预处理器完成其工作后处理的。 The preprocessor ignores this line.预处理器忽略这一行。

There is no direct way to do what you want;没有直接的方法可以做你想做的事; the ideal solution is to arrange your project in a way that HP will never be declared more than once.理想的解决方案是以永远不会多次声明HP的方式安排您的项目。 It should be declared in a single translation unit, and exposed as extern in header files.它应该在单个翻译单元中声明,并在 header 文件中显示为extern

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

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