Strange #ifdef variable issue

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?

Last edited on
You can't assign to any variables globally, unless you do it while declaring it.
Do not use a name like _DEBUGFLAG anywhere in your code;
such names are reserved for use by the implementation.

We can have a name with a leading underscore in our code provided that
a. the name is not in the global namespace
b. the leading underscore is not followed by another underscore or an upper case letter.


This would be fine at global scope:

1
2
3
4
5
6
const int debug_code =
#ifdef DEBUGFLAG
                          1 ;
#else
                          0 ;
#endif // DEBUGFLAG 


Last edited on
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?

Basically, all you can do in the global scope is declare and define things (*). So, you can declare variables, define types, define classes, define functions... but you can't have any further lines of code that actually perform any operations.

This means that you can initialise a global variable at global scope, because initialisation is part of declaration. Hence:

int debug_code = 1;

is fine. But you can't assign to a variable at global scope. So:

debug_code = 1;

is not.

(*) That's probably a simplification, but it captures the essense of what you can and can't do.
Last edited on
Topic archived. No new replies allowed.