The #define and #undef are compiler directives. They are part of the preprocessing of the code and are ran independent of where they are put in relation of the "real" code.
Basically, before the compiler run your code it goes through every directive (#include, #define, #ifdef) and preprocesses your code, so, for example, when you do:
int firstVariable = MY_DIRECTIVE;
#define MY_DIRECTIVE 7
int doesNothing = 9;
int myVariable = MY_DIRECTIVE;
#undef MY_DIRECTIVE
int thirdVariable = MY_DIRECTIVE;
it transforms it in:
int firstVariable = MY_DIRECTIVE;
int doesNothing = 9;
int myVariable = 7;
int thirdVariable = MY_DIRECTIVE;
And only after it will compile your code (in this case giving you a error that MY_DIRECTIVE hadn't been defined on line 1 and 7)
For more info:
Preprocessor directives (cplusplus)