Generally speaking, executable code (ie: code that actually does something) can only be inside of functions.
Your cout statement on line 6 is executable. That is, it will actually print out something. Therefore it has to go in a function, and will only happen when that function is executed. You can't just put it in the middle of a header like that -- it doesn't make any sense.
Also, how does #ifndef and #ifdef works? |
1 2 3
|
#ifdef FOO
body
#endif
|
The precompiler will look to see if the symbol FOO has been #defined. If it
has, it will proceed normally, if it
hasn't, it will essentially delete/ignore everything up to the matching #endif.
In this example, 'body' will be skipped over unless FOO has been #defined.
#ifndef
is the same thing, only in reverse. If the symbol
has been defined, then the code is skipped. If it
hasn't been defined, then it proceeds normally.
Yes, but it doesn't make sense:
1 2 3 4 5 6 7 8 9 10 11
|
#ifndef FOO_H // <- only proceed if FOO_H has not been defined
#define FOO_H // <- in which case, define it
do something...
#ifdef FOO_H // <- we just defined it, so of course it will be defined here
do something...
#endif // <- end of line 6's #ifdef
#endif // <- end of line 1's #ifndef
|
if so, how does compiler know which one ends first? |
It's a stack. First in, last out.
#endif will close the "inner most" #if/#ifdef/#ifndef