StudentX
StudentX

Reputation: 2323

Include header files in c++

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"

Upvotes: 1

Views: 453

Answers (1)

BoBTFish
BoBTFish

Reputation: 19767

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();
}

Upvotes: 1

Related Questions