简体   繁体   中英

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

I defined const UInt8 HE = he; inside namespace Ports in ports.h . Then I included it in ports_logic.h and in ports_logic.h , I have the following code inside 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?

Thanks.

Briefly, const UInt8 HP = hp; does not introduce a pre-processor identifier on which #ifndef HP could ever react on.

Identifiers defined through #define preprocessor directive and the definition of variables are two different things. 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.

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. 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. The C++ compiler never sees this line.

const UInt8 HP = hp;

This is handled by the C++ compiler after the preprocessor has done its thing. 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. It should be declared in a single translation unit, and exposed as extern in header files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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