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?
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?
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.:
My rationale for 1. is that it should prove that each header (for which there is a cpp) can be #include
d without prerequisites (technically speaking: header is "self-contained"). And the rest just seems to flow logically from there.
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 #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 #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 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:
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.
I follow two simple rules that avoid the vast majority of problems:
I also follow the guidelines of:
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 :-)
To add my own brick to the wall.
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:
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.
#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 .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 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 I recommend:
And of course, alphabetical order within each section, where possible.
Always use forward declarations to avoid unnecessary #include
s in your header files.
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.
windows.h
. –
Overmodest This is not subjective. Make sure your headers don't rely on being #include
d in specific order. You can be sure it doesn't matter what order you include STL or Boost headers.
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
.
Several separate considerations are conflated when deciding for a particular include order. Let try to me untangle.
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.
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.
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.
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.
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.
© 2022 - 2024 — McMap. All rights reserved.