Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#include header style

Tags:

c++

I have a question regarding "best-practice" when including headers.

Obviously include guards protect us from having multiple includes in a header or source file, so my question is whether you find it beneficial to #include all of the needed headers in a header or source file, even if one of the headers included already contains one of the other includes. The reasoning for this would be so that the reader could see everything needed for the file, rather than hunting through other headers.

Ex: Assume include guards are used:

// Header titled foo.h
#include "blah.h"
//....

.

// Header titled bar.h that needs blah.h and foo.h
#include "foo.h"
#include "blah.h" // Unnecessary, but tells reader that bar needs blah

Also, if a header is not needed in the header file, but is needed in it's related source file, do you put it in the header or the source?

like image 783
trikker Avatar asked Oct 28 '09 00:10

trikker


1 Answers

In your example, yes, bar.h should #include blah.h. That way if someone modifies foo so that it doesn't need blah, the change won't break bar.

If blah.h is needed in foo.c but not in foo.h, then it should not be #included in foo.h. Many other files may #include foo.h, and more files may #include them. If you #include blah.h in foo.h, then you make all those files needlessly dependent on blah.h. Needless dependencies cause lots of headaches:

  • If you modify blah.h, all those files must be recompiled.
  • If you want to isolate one of them (say, to carry it over to another project or build a unit test around it) you have to take blah.h along.
  • If there's a bug in one of them, you can't rule out blah.h as the cause until you check.
  • If you are foolish enough to have something like a macro in blah.h... well, never mind, in that case there's no hope for you.
like image 95
Beta Avatar answered Sep 28 '22 10:09

Beta