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

219 Views Asked by At

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.

enter image description here

What is the alternative to ifndef that can help me check if the const int HP has already been defined?

Thanks.

2

There are 2 best solutions below

0
tenfour On

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.

0
Stephan Lechner On

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