Using cout in header file...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef FOO_H
#define FOO_H
#include <iostream>


std::cout << "FOO_H not defined" << std::endl;
class Foo{
    public:
        Foo();
    private:
    protected:
};

#endif 


I'm not sure why I'm getting an error that says 'std does not name a type'.

Also, how does #ifndef and #ifdef works?

1
2
3
4
5
6
7
8
9
10
11
#ifndef FOO_H
#define FOO_H

do something...

#ifdef FOO_H

do something...

#endif
#endif 



is this possible?
if so, how does compiler know which one ends first?
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.


is this possible?


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
> I'm not sure why I'm getting an error that says 'std does not name a type'.

std::cout << "FOO_H not defined" << std::endl is being used as the discarded-value expression of an expression statement. (The expression is evaluated and its value is then thrown away).

Instead, use the expression as (part of) an initializer.
(The expression is evaluated and its value is then used to initialise a variable.)

1
2
3
4
5
6
7
8
9
10
11
12
#ifndef FOO_H
#define FOO_H

#include <iostream>

const bool not___defined___ = bool( std::cout << "FOO_H not defined" << std::endl );

class Foo{
    // ...
};

#endif // FOO_H 
Last edited on
Topic archived. No new replies allowed.