Maxpm
Maxpm

Reputation: 25592

Mutual Inclusion of Header Files

Let's say I have a header file called inclusions.h that has all the #include <...>s for my project. inclusions.h includes another header file called settings.h, where various constants can be modified.

If #include <math.h> in inclusions.h, will settings.h have access to the math library as well? Or do I have to #include <math.h> in settings.h as well?

Upvotes: 1

Views: 2372

Answers (3)

tyree731
tyree731

Reputation: 483

In this case, as others have noted, depending on the order of inclusion it could be accessible. This is because those source files are a part of one translation unit (source + includes essentially) so if <math.h> comes before "settings.h", it could be viewable by it. However, if settings became a part of another translation unit, or if you decided to move certain includes around that could change. To be "safe", you should just included whatever header files which are necessary for a file to have in that file.

Upvotes: 1

UncleZeiv
UncleZeiv

Reputation: 18488

It depends on the order of the inclusions. #include is a preprocessor directive that simply works by textual substitution. So, if in inclusions.h you have:

#include <math.h>
#include <settings.h>

settings "can see" math. If you have:

#include <settings.h>
#include <math.h>

it can't. But: what would happen if you used settings.h elsewhere without including math.h before? So in the end, try to make each include file independent.

Upvotes: 3

Flinsch
Flinsch

Reputation: 4340

If math.h is included before settings.h, settings.h should also have access to math.h. But to ensure the access (and to indicate the dependencies), you should include the files where they are needed, so also in math.h.

Upvotes: 5

Related Questions