1

The C++ Premier I have doesn't say much about what I am about to ask, and this is what I got googling LINK:

When the compiler compiles the #include "example.h" line, it copies the contents of example.h into the current file.

So, if that's true, in the following example why B.h doesn't know about A.h ? Is it how the files are compiled ? Do I have to include A.h in every file that use it and then include every file that use A.h in the program.h that uses these files ?

In program.h
#include "A.h"
#include "B.h"
1
  • 1
    It does! But it is good practice to include a header directly whenever you need it. Commented Jun 13, 2013 at 14:51

1 Answer 1

1

WARNING: VERY BAD CODE:

a.h

#ifndef A_H
#define A_H

#define SOME_LIT "string lit in A.h"

#endif

b.h

#ifndef B_H
#define B_H

#include <iostream>

void foo() { std::cout << SOME_LIT << '\n'; }

#endif

main.cpp

#include "a.h"
#include "b.h"

int main()
{
    foo();
}

Prints:

$ ./a.out 
string lit in A.h

So you can see b.h knows about the define in a.h. If you forgot the #include "a.h", or put it below #include "b.h", this would break.

As a general rule however, you should explicitly #include a header in any file you need it. That way you know that you only care about foo in main, so you just #include the foo header, which is b.h:

#include "b.h"
int main()
{
    foo();
}
Sign up to request clarification or add additional context in comments.

9 Comments

That's strange, it didn't work for me, for a mvc project I am working, I have numerous subclasses in their separate files, and the base class in it's separate file, then in the controller class file, I am doing something like : #include "basefile.h" #include "child1.h" #include "child2.h" and so on.. but I get compile time errors stating that baseclass doesn't doesn't name a type in child1.h(or something similar)
Well, b.h only knows about the define in a.h in the context of main.cpp in your example. If only b.h is included, you'll get errors.
2 possibilities: 1) You don't have your compilation configured correctly so it can't pick up one of the headers. 2) You have made a mistake in the order you include things. I think 2 is the more common problem. This is why it is recommended to always include everything you need in the file in which you use it.
@PureW Yes, that is exactly the question. Was that not clear? Also why I included the warning and the recommendation at the end.
I don't know how to do it in msvc, but if you can use g++ or clang++, use the -E command line option to just apply the preprocessing. Then you can see that #includes are literally just pasted in.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.