Behavior similar to that in the question can be seen when using #define
s that are strings, not integers.
The following code seems like it should run Code();
only when MODE
is equal to the string different
:
mode.h
#define MODE something
different.cpp
#include "mode.h"
#if MODE == different
Code();
#endif
Eclipse shows Code();
as being active when it appears it should be inactive. The reason for this is that the preprocessor does not support string comparisons, only integer ones1.
When mousing over MODE
in different.cpp
, MODE
is shown as having the value something
. Although this is technically correct, it can be misleading since both MODE
and something
evaluate to the same thing (a defined but empty value). Given that they both have the same value (nothing) they evaluate as being equal and Code();
is run.
1 This is gone into in more detail in this question.
Solutions
Two possible ways of correctly handling this come to mind:
- Assign numeric values to each option
- Use unique
#define
s for each option
Use numeric values
The code could be written as follows:
mode.h
#define MODE_something 0
#define MODE_different 1
#define MODE MODE_something
different.cpp
#include "mode.h"
#if MODE == MODE_different
Code();
#endif
In this case the code works as expected since MODE
and MODE_different
evaluate to two distinct values (0
and 1
, respectively).
Use unique #define
s
Another approach is to use uniquely-named macros for each option. For example:
mode.h
// Select the active mode:
#define MODE_something
//#define MODE_different
different.cpp
#include "mode.h"
#ifdef MODE_different
Code();
#endif