tags:

views:

827

answers:

9

Hello.

Is there recommended order in which include files should be specified?

For example, the system files, STL, Boost, go before of after local include files? is there a particular reason to choose one or another? I am assuming include files have proper dependencies specified.

Thanks

+3  A: 

This is not subjective. Make sure your headers don't rely on being #included in specific order. You can be sure it doesn't matter what order you include STL or Boost headers.

wilhelmtell
I was assuming no implicit dependencies
aaa
+20  A: 

I don't think there's a recommended order, as long as it compiles! What's annoying is when some headers require other headers to be included first... That's a problem with the headers themselves, not with the order of includes.

My personal preference is to go from local to global, each subsection in alphabetical order, i.e.:

  1. h file corresponding to this cpp file (if applicable)
  2. headers from the same component,
  3. headers from other components,
  4. system headers.

My rationale for 1. is that it should prove that each header (for which there is a cpp) can be #included without prerequesites. And the rest just seems to flow logically from there.

squelart
Pretty much the same as you, except I go from global down to local, and the header corresponding to the source file doesn't receive special treatment.
Jon Purdy
Yeah, I adopted the same style for the same reasons. I've still yet to find it bad practice.
Matt Joiner
@Jon: I'd say that's pretty much the opposite! :-) I would argue that your method can introduce hidden dependencies, say if myclass.cpp includes <string> then <myclass.h>, there's no way to catch at build time that myclass.h may itself depend on string; so if later on you, or someone else, includes myclass.h but don't need string, you'll get an error that needs to be fixed either in the cpp or in the header itself.But I would be interested to know if that's what people think would work better in the long run... Why don't you post an answer with your proposal and we'll see who "wins"? ;-)
squelart
The specific to general ordering is what I use at this time from the recommendation of Dave Abrahams. And he notes the same reason as @squelart of illuminating missing header includes in sources, from local to more general. The important key being that you are more likely to make those mistakes than 3rd party, and system libraries.
GrafikRobot
@Grafik: Interesting, could you please give a link to Dave Abrahams' recommendations? (if there's such a page) -- Tried a bit of Googling but couldn't find anything...
squelart
@squelart -- I can't link to it.. Since it was a phone conversation I had with him a few years ago.
GrafikRobot
thank you. I think I am going to do your style.
aaa
I prefer system headers as number 2. What happens if one of the headers from 2 or 3 does something silly that alters the interpretation of a system header?
Ben
@Ben: I see your point, but I'm not sure that your solution is really helping in the end: Either a system header is itself relying on things it shouldn't (unlikely), or the faulty local header is screwing things up so badly that it would probably impact on other code as well and therefore should be fixed! If we stick with the principle that headers should be created so that they *can* be included in any order, then I'd still prefer my solution as it's more likely to highlight dependency issues earlier... Would you have a real-life example where including system headers 1st or 2nd is necessary?
squelart
+6  A: 

I'm pretty sure this isn't a recommended practice anywhere in the sane world, but I like to line system includes up by filename length, sorted lexically within the same length. Like so:

#include <set>
#include <vector>
#include <algorithm>
#include <functional>

I think it's a good idea to include your own headers before other peoples, to avoid the shame of include-order dependency.

spong
+1. I especially like the second suggestion.
Potatoswatter
I like second, first not so much
aaa
I like to sort my headers by using a key consisting of the second, third then first letter in that order :-) So vector, set, algorithm, functional for your example.
paxdiablo
@paxdiablo, thanks for the tip. I'm considering using it, but I'm concerned that it may end up leaving the pile of filenames unstable and likely to tip over. Who knows what might be included if this happens - perhaps even `windows.h`.
spong
Sorted by _length_? Insanity!
James McNellis
+1 for the second, -1 for the first: result 0
dcw
+1 for the first. It makes sense actually, if you need to visually locate headers within a file with your eyes it is a lot better than alphabetical.
Kugel
+7  A: 

I follow two simple rules that avoid the vast majority of problems:

  1. All headers (and indeed any source files) should include what they need. They should not rely on their users including things.
  2. As an adjunct, all headers should have include guards so that they don't get included multiple times by over-ambitious application of rule 1 above.

I also follow the guidelines of:

  1. Include system headers first (stdio.h, etc) with a dividing line.
  2. Group them logically.

In other words:

#include <stdio.h>
#include <string.h>

#include "btree.h"
#include "collect_hash.h"
#include "collect_arraylist.h"
#include "globals.h"

Although, being guidelines, that's a subjective thing. The rules on the other hand, I enforce rigidly, even to the point of providing 'wrapper' header files with include guards and grouped includes if some obnoxious third-party developer doesn't subscribe to my vision :-)

paxdiablo
This is practically word-for-word the answer that I had begun to type. +1
Daniel Stutzbach
+1 "All headers (and indeed any source files) should include what they need. They should not rely on their users including things." Yet so many people rely on this implicit inclusion behavior, for instance, with NULL and don't include <cstddef>. It's so annoying when trying to port this code and getting compile errors on NULL (one reason I just use 0 now).
+5  A: 

I recommend:

  1. The header for the .cc module you're building. (Helps ensure each header in your project doesn't have implicit dependencies on other headers in your project.)
  2. C system files.
  3. C++ system files.
  4. Platform / OS / other header files (e.g. win32, gtk, openGL).
  5. Other header files from your project.

And of course, alphabetical order within each section, where possible.

Always use forward declarations to avoid unnecessary #includes in your header files.

jeffamaphone
this is what I do
Kugel
+1, but why alphabetical? Seems like something that may make you feel better, but has no practical benefit.
Ben
+1  A: 

First include the header corresponding to the .cpp... in other words, source1.cpp should include source1.h before including anything else. The only exception I can think of is when using MSVC with pre-compiled headers in which case, you are forced to include stdafx.h before anything else.

Reasoning: Including the source1.h before any other files ensures that it can stand alone without it's dependencies. If source1.h takes on a dependency on a later date, the compiler will immediately alert you to add the required forward declarations to source1.h. This in turn ensures that headers can be included in any order by their dependants.

Example:

source1.h

class Class1 {
    Class2 c2;    // a dependency which has not been forward declared
};

source1.cpp

#include "source1.h"    // now compiler will alert you saying that Class2 is undefined
                    // so you can forward declare Class2 within source1.h
...

MSVC users: I strongly recommend using pre-compiled headers. So, move all #include directives for standard headers (and other headers which are never going to change) to stdafx.h.

Vulcan Eager
A: 

I consider this a purely stylistic concern, since headers should have as few dependencies as possible, and consequently forward-declare as much as possible, relying on source files to supply dependencies for what they actually use non-referentially. Basically the only time I ever include something in a header is when the needed class cannot be forward-declared, which is the case pretty much exclusively for system headers and inherited classes. You can get around the whole issue of inclusion order by designing your headers correctly in the first place.

So, for the sake of having some arbitrary consistent order, I write #includes top-down:

  • System headers.
  • Boost headers.
  • Library headers.
  • Project headers.

Each section is sorted lexicographically, case-sensitively: files beginning with a come after those beginning with Z. Since my class headers are in CamelCase and utility headers are in lowercase, these naturally fall into groups within the project headers. The header for the class that is implemented in the including source file has no special significance and is sorted along with other project headers.

You can introduce implicit dependencies this way. It is not foolproof. But defensive programming is really fearful programming, and the only way to quit being a fool when programming is to program without fear, accept the consequences for doing it wrong, and learn from your mistakes.

Jon Purdy
I've learned from my mistakes that I should program defensively in order to make less mistakes :-)
squelart
If you do least specific -> most specific you (strongly) run the risk of creating header files that are not self-contained, potentially leaving users of your components in quite a confusion.
dcw
@squelart: That's perfectly valid. People program differently and I'm not out to change that. This is something that works for me, for now, but I can always change. I may have controversial opinions, but I think a little healthy discussion is good for people, and honestly I'd much rather be downvoted than silent.
Jon Purdy
A: 

Include from the most specific to the least specific, starting with the corresponding .hpp for the .cpp, if one such exists. That way, any hidden dependencies in header files that are not self-sufficient will be revealed.

This is complicated by the use of pre-compiled headers. One way around this is, without making your project compiler-specific, is to use one of the project headers as the precompiled header include file.

dcw
+4  A: 

To add my own brick to the wall.

  1. Each header needs to be self-sufficient, which can only be tested if at least once it's included first
  2. One should not mistakenly modify the meaning of a 3rd party header by introducing symbols (macro, types, etc...)

So I usually go like this:

// myproject/src/example.cpp
#include "myproject/example.h"

#include <algorithm>
#include <set>
#include <vector>

#include <3rdparty/foo.h>
#include <3rdparty/bar.h>

#include "myproject/another.h"
#include "myproject/specific/bla.h"

#include "detail/impl.h"

Each group separated by a blank line from the next one:

  • Header corresponding to this cpp file first (sanity check)
  • system headers
  • 3rd party headers, organized by dependency order
  • project headers
  • project private headers

Also note that apart from system headers each file is in a folder that with the name of its namespace, just because it's easier to track them down this way.

Matthieu M.
This is exactly what I do, though, I hadn't thought about the rational until now.
caspin