C/C++ include header file order [closed]
Asked Answered
B

11

376

What order should include files be specified, i.e. what are the reasons for including one header before another?

For example, do the system files, STL, and Boost go before or after the local include files?

Bazooka answered 4/5, 2010 at 3:9 Comment(3)
And the plethora of answers below is why the Java developers decided against separate headers. :-) Some really good answers, however, particularly the admonition to make sure your own header files can stand alone.Measurable
I like it how questions that have 100+ votes and are obivously interesting for quite some people get closed as "not constructive".Precocity
A highly recommended read: cplusplus.com/forum/articles/10627Manned
H
400

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 prerequisites (technically speaking: header is "self-contained"). And the rest just seems to flow logically from there.

Helio answered 4/5, 2010 at 3:17 Comment(20)
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.Mozza
Yeah, I adopted the same style for the same reasons. I've still yet to find it bad practice.Dextroamphetamine
@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"? ;-)Helio
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 @Helio 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.Harleyharli
@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...Helio
@Helio -- I can't link to it.. Since it was a phone conversation I had with him a few years ago.Harleyharli
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?Irrecoverable
@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?Helio
I like this expression go from local to globalCreepy
I follow this method (local to global), however, I have read that it increases compilation time. I also think I heard it was to do with templates, any idea?Monmouth
@Copperpot I suppose it might be slower because more-global headers will have to be preprocessed in different contexts in each compilation units, as previous #includes differ every time (if your build system is able to automagically optimise for situations where #includes are similar in different files). The usual solution, depending on your build env or IDE, would be to have a preprocessed header including most system headers and possibly some important project-related headers, so that they are only processed once per build. But only guessing here, anyone else with experience please weigh in.Helio
The proposed order of header files in this answer is dangerous. Suppose a system header file is defining some macro FOO. This is typically done by means of #undef FOO followed by #define FOO somevalue. If you have defined your own #define FOO someothervalue to overrule the standard behavior it will still use the system #define FOO somevalue in this case because the system header is included as last header file.Mercurialism
@PaulJansen That's a bad practice and it's good to use a technique that is more likely to blow up with it so that the bad practice can be fixed instead of laying hidden. local to global FTWDivest
@Divest Just for my understanding. What is bad practice? Using #undef FOO followed by #define FOO somevalue? This is something in system header files I can't change. If you are referring to "overruling the standard behavior", then please realize that this also could happen by accident. You might end up with unexpected results in such a case.Mercurialism
@PaulJansen Yes, I was referring to overruling standard behavior. It could happen by accident just as, for example, breaking the ODR can happen by accident. The solution is not to use practices that hide when such accidents happen, but to use practices that are most likely to make them blow up as loudly as possible, so that the mistakes can be noticed and fixed as early as possible.Divest
I actually do the opposite here, for the most part. I put STL headers first, then boost, then all other third party headers. After that I put includes in the component/module/library I'm in. I do this so that macros and symbols with similar names clash at the local level and do not cause errors in STL/boost/etc. STL's definitions take top priority over everything else. The only one I put above STL is the corresponding H file include. This is so that I make sure my H files manage their own header dependencies properly.Freberg
Not mentioned in the answer, but yet another reason to go from local to global: Feature Test Macros, if present, must be defined before any standard library header is included. FTMs usually go into some kind of config.h file. Therefore, this case folds perfectly into the general rule: local config.h file before global standard header.Attendance
@PaulJansen In addition if you really want to override some define or something from system header anyway, your header file is dependent on the system header and should have included it already. Anyway header files that actually depends on the include order is bad.Communism
@skyking, I'd say it's helpful to have the standard library headers first as if something conflicts with them, then this is where the error appears. And, as @PaulJensen mentions, those files often contain #undef which can have unintended consequences, and may not give an error. It is easy to detect these kind of things up front rather than relying on static analysis which may run later (and might still not catch the issue).Bello
I tried your suggestion, and it's excellent. You can apply the changes one by one, for each '.h' and '.cpp' pair. When something fails, it's because there was an underlying, hidden bug, and it's usually easy to fix. I found a few hidden or unused dependencies this way. Compilation is faster, but more importantly, the code is cleaner and the headers are very lean. Thanks!Sailplane
R
163

The big thing to keep in mind is that your headers should not be dependent upon other headers being included first. One way to insure this is to include your headers before any other headers.

"Thinking in C++" in particular mentions this, referencing Lakos' "Large Scale C++ Software Design":

Latent usage errors can be avoided by ensuring that the .h file of a component parses by itself – without externally-provided declarations or definitions... Including the .h file as the very first line of the .c file ensures that no critical piece of information intrinsic to the physical interface of the component is missing from the .h file (or, if there is, that you will find out about it as soon as you try to compile the .c file).

That is to say, include in the following order:

  1. The prototype/interface header for this implementation (ie, the .h/.hh file that corresponds to this .cpp/.cc file).
  2. Other headers from the same project, as needed.
  3. Headers from other non-standard, non-system libraries (for example, Qt, Eigen, etc).
  4. Headers from other "almost-standard" libraries (for example, Boost)
  5. Standard C++ headers (for example, iostream, functional, etc.)
  6. Standard C headers (for example, cstdint, dirent.h, etc.)

If any of the headers have an issue with being included in this order, either fix them (if yours) or don't use them. Boycott libraries that don't write clean headers.

Google's C++ style guide argues almost the reverse, with really no justification at all; I personally tend to favor the Lakos approach.

Reluct answered 9/1, 2013 at 18:8 Comment(5)
As of now, Google C++ Style Guide recommends including the related header file first, following Lakos' suggestion.Morris
You don't get much beyond the first related header because once you start including your in-project headers you are going to pull in a lot of system dependencies.Protect
@Protect - in-project headers pulling in "a lot of system dependencies" is bad design, precisely what we're trying to avoid here. The point is to avoid both unnecessary includes and unresolved dependencies. All headers should be able to be included without including other headers first. In the case where an in-project header needs a system dependency, so be it - then you don't (and shouldn't) include the system dependency after it, unless the code local to that file uses things from that system dep. You cannot and should not rely on headers (even yours) to include system deps that you use.Reluct
@NathanPaulSimons headers being self-contained means they have to include any and all dependencies necessary to achieve that, including "a lot of system dependencies". Yes, they should minimize it, but that's still often quite a lot.Yarborough
@FilipBártek, the Google recommendation is exactly why I, for one, landed here, looking for insights. The Google guide doesn't give the rationale for it, while they do also add another "rule" like "Within each section the includes should be ordered alphabetically." Which is quite simply: stupid. Such a pointless, brittle, unrealistic, counterintuitive, even counterproductive chore can only mandate yet more extra tooling (for nothing, i.e. to make other tools (like linters) happy), or will be violated all the time (with no ill effect).Amphisbaena
R
53

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 :-)

Reagan answered 4/5, 2010 at 3:26 Comment(8)
+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).Erubescence
Why do you include system headers first? It would be better the other why around because of your first rule.Heiress
If you use Feature Test Macros, your first include most probably should NOT be a standard library header. Therefore, for generality, I'd say the "local first, global later" policy is best.Attendance
Regarding your first suggestion of "not relying on users ", what about forward declarations in header file which don't need the header file to be included ? Should we still be including the header file because forward declarations put the onus on the user of the header file to include the appropriate files.Harrington
@Heiress If you include another in-project or third-party header before a system header, then Feature Test Macros (or similar preprocessor stuff) used in that other header might break your translation unit inadvertently. You should include the system headers you use exactly as you want to use them, and only then include other stuff, and hope that the other stuff is well-designed so that it doesn't break by your usage of system headers. That way, you can hopefully notice what is the first include that breaks stuff, and it will be that header that should be fixed. So I stand by Google's order.Childress
@alx I avoid that by prefixing any macros I define in header files. If your headers break system includes you will run into problems anyway as soon as you start doing stuff like unity builds, etc.Heiress
@Heiress I mean using standard macros (e.g., _POSIX_SOURCE), not your own macros. I had a conflict a few years ago while using ncurses and opencv at the same time, because one of them defined a macro that had a meaningful name for the other, and stuff breaks, and it's hard to find the source of the problem. Since the compiler starts complaining at the first inconsistency that it finds, and since we can rely on system headers (usually) having less bugs than other libraries headers, and other libs headers less than the project's headers, it's easier to find the bug including in that order.Childress
@Heiress And of course, you can control your own headers (although everyone makes mistakes, but of course we try to avoid them), but not third party ones, which may and will be buggy.Childress
T
30

To add my own brick to the wall.

  1. Each header needs to be self-sufficient, which can only be tested if it's included first at least once
  2. One should not mistakenly modify the meaning of a third-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
  • Third-party headers, organized by dependency order
  • Project headers
  • Project private headers

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

Thrombo answered 4/5, 2010 at 6:38 Comment(5)
So that other header files aren't affected by them. Both by what those system headers define (both X includes and Windows includes are bad about #define's that mess up other code) and to prevent implicit dependencies. For example, if our code base header file foo.h really depends on <map> but everywhere it was used in .cc files, <map> happened to already be included, we probably wouldn't notice. Until someone tried to include foo.h without first including <map>. And then they'd be annoyed.Reversal
@0A0D: The second issue is not a problem in the order here, because each .h has at least one .cpp that includes it first (indeed, in my personal code the Unit test associated includes it first, and the source code includes it in its rightful group). Regarding not being influenced, if any of the headers includes <map> then all headers included afterwards are influenced anyway, so it seems a losing battle to me.Thrombo
Of course, which is why I regularly go around and correct older code (or even newer code) which requires an unnecessary include because it just drives up build times.Reversal
@MatthieuM. I would like to know the rationale behind your point one i.e. Header corresponding to this cpp file first (sanity check). Is there anything particular if #include "myproject/example.h" is moved to the end of all includes?Zellers
@MNS: A header should be free-standing, that is, it should not be required to include any other header before it. It is your responsibility, as the writer of the header, to make sure of this, and the best way to do so is to have one source file in which this header is included first. Using the source file corresponding to the header file is easy, another good choice is using the unit test source file corresponding to the header file but it is less universal (there may not be unit tests).Thrombo
D
18

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.

Damalis answered 4/5, 2010 at 3:36 Comment(3)
+1, but why alphabetical? Seems like something that may make you feel better, but has no practical benefit.Irrecoverable
Alphabetical is an arbitrary ordering, but an easy one. You don't have to do alphabetical, but you have to pick some ordering so that everyone does it consistently. I've found it helps avoid duplicates and makes merges easier. And if you use sublime text, F5 will order them for you.Damalis
I'm definitely a fan of the system/library files first approach, reason being that if something in those files gets redefined, then the error appears in the file that does the redefinition. Otherwise the error appears in a file that is part of the standard library or somewhere that you can't easily change. Of course, having the include for the module at the top isn't consistent with this, but then having headers that are self contained can save a lot of trouble too and it is easy to miss something.Bello
O
17

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.

Overmodest answered 4/5, 2010 at 3:24 Comment(6)
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.Reagan
@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.Overmodest
Sorted by length? Insanity!Senhorita
+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.Lashio
This answer only partially addresses the issue of the original question. And I think this is a very uncommon way to do this, I have never seen it.Sheathe
@Lashio it's easier to manually sort headers by length, but code is read more than it is written: If you include lots of headers, off the top of your head do you know that vector is shorter or longer than utility?Irrecoverable
K
7

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.

Knisley answered 4/5, 2010 at 3:12 Comment(2)
I was assuming no implicit dependenciesBazooka
Yes, but the compiler can't make this assumption, so #include <A>,<B> is never the the same as #include <B>,<A> until they have been compiled.Rizo
W
5

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.

Weimer answered 4/5, 2010 at 3:46 Comment(0)
R
4

Several separate considerations are conflated when deciding for a particular include order. Let try to me untangle.

1. check for self-containedness

Many answers suggest that the include order should act as a check that your headers are self-contained. That mixes up the consideration of testing and compilation

You can check separately whether your headers are self-included. That "static analysis" is independent of any compilation process. For example, run

gcc headerfile.h -fsyntax-only

Testing whether your header files are self-contained can easily be scripted/automated. Even your makefile can do that.

No offense but Lakos' book is from 1996 and putting those different concerns together sounds like 90s-style programming to me. That being said, there are ecosystems (Windows today or in the 90s?) which lack the tools for scripted/automated tests.

2. Readability

Another consideration is readability. When you look up your source file, you just want to easily see what stuff has been included. For that your personal tastes and preferences matter most, though typically you either order them from most specific to least specific or the other way around (I prefer the latter).

Within each group, I usually just include them alphabetically.

3. Does the include order matter?

If your header files are self-contained, then the include order technically shouldn't matter at all for the compilation result.

That is, unless you have (questionable?) specific design choices for your code, such as necessary macro definitions that are not automatically included. In that case, you should reconsider your program design, though it might work perfectly well for you of course.

Representation answered 24/5, 2021 at 0:16 Comment(1)
Well, there is the mistake of redefining something in the standard library, or in one of your other external libraries. In any case, your code won't compile. But if you use the order standard libraries, external libraries, project includes, then the error will helpfully appear in the line that does the redefinition (or hopefully at least has a definition you can change). Modern compilers will usually at least tell you where both definitions are, but even then I still find it helps.Bello
L
3

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.

Lehet answered 4/5, 2010 at 5:47 Comment(0)
C
1

It is a hard question in the C/C++ world, with so many elements beyond the standard.

I think header file order is not a serious problem as long as it compiles, like squelart said.

My ideas is: If there is no conflict of symbols in all those headers, any order is OK, and the header dependency issue can be fixed later by adding #include lines to the flawed .h.

The real hassle arises when some header changes its action (by checking #if conditions) according to what headers are above.

For example, in stddef.h in VS2005, there is:

#ifdef  _WIN64
#define offsetof(s,m)   (size_t)( (ptrdiff_t)&(((s *)0)->m) )
#else
#define offsetof(s,m)   (size_t)&(((s *)0)->m)
#endif

Now the problem: If I have a custom header ("custom.h") that needs to be used with many compilers, including some older ones that don't provide offsetof in their system headers, I should write in my header:

#ifndef offsetof
#define offsetof(s,m)   (size_t)&(((s *)0)->m)
#endif

And be sure to tell the user to #include "custom.h" after all system headers, otherwise, the line of offsetof in stddef.h will assert a macro redefinition error.

We pray not to meet any more of such cases in our career.

Cristoforo answered 16/12, 2011 at 1:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.