I am getting some interesting compiler errors when I attempt to use a declared global variable inside an ifdef. See code:
1 2 3 4 5 6
|
int debug_code;
#ifdef _DEBUGFLAG
debug_code = 1;
#else
debug_code = 0;
#endif
|
Using g++ compiler, (although this same issue occurs on other C++ compilers) I get the following error:
1 2 3
|
error: debug_code does not name a type
in reference to line: debug_code = 0 under the #else
|
I found the obvious workaround for this, but it involves declaring the same variable in each block.
1 2 3 4 5
|
#ifdef _DEBUGFLAG
int debug_code = 1;
#else
int debug_code = 0;
#endif
|
This seems to work fine. But why doesn't the first way work as intended? On further investigation, I tried running the original problematic #ifdef code through the G++ compiler with the flag for the preprocessor only. No errors.
I also tried placing the #ifdef blocks inside a function, such as main to see if the same error would occur. It did not.
1 2 3 4 5 6 7 8 9
|
int main()
{
int debug_code;
#ifdef _DEBUGFLAG
debug_code = 1;
#else
debug_code = 0;
#endif
}
|
This compiled and worked as intended.
So it remains a mystery - why does the compiler refuse to compile the first scenario & claim declaration error, where a variable is declared globally above the #ifdef and then used inside the ifdef block?