C/C++ include header file order - c++

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.:
h file corresponding to this cpp file (if applicable)
headers from the same component,
headers from other components,
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 (terminus technicus: header is "self-contained"). And the rest just seems to flow logically from there.

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:
The prototype/interface header for this implementation (ie, the .h/.hh file that corresponds to this .cpp/.cc file).
Other headers from the same project, as needed.
Headers from other non-standard, non-system libraries (for example, Qt, Eigen, etc).
Headers from other "almost-standard" libraries (for example, Boost)
Standard C++ headers (for example, iostream, functional, etc.)
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.

I follow two simple rules that avoid the vast majority of problems:
All headers (and indeed any source files) should include what they need. They should not rely on their users including things.
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:
Include system headers first (stdio.h, etc) with a dividing line.
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 :-)

To add my own brick to the wall.
Each header needs to be self-sufficient, which can only be tested if it's included first at least once
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.

I recommend:
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.)
C system files.
C++ system files.
Platform / OS / other header files (e.g. win32, gtk, openGL).
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.

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.

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.

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.

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.

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.

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.

Related

System headers before other headers according to Google Style guide? [duplicate]

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.:
h file corresponding to this cpp file (if applicable)
headers from the same component,
headers from other components,
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 (terminus technicus: header is "self-contained"). And the rest just seems to flow logically from there.
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:
The prototype/interface header for this implementation (ie, the .h/.hh file that corresponds to this .cpp/.cc file).
Other headers from the same project, as needed.
Headers from other non-standard, non-system libraries (for example, Qt, Eigen, etc).
Headers from other "almost-standard" libraries (for example, Boost)
Standard C++ headers (for example, iostream, functional, etc.)
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.
I follow two simple rules that avoid the vast majority of problems:
All headers (and indeed any source files) should include what they need. They should not rely on their users including things.
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:
Include system headers first (stdio.h, etc) with a dividing line.
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 :-)
To add my own brick to the wall.
Each header needs to be self-sufficient, which can only be tested if it's included first at least once
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.
I recommend:
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.)
C system files.
C++ system files.
Platform / OS / other header files (e.g. win32, gtk, openGL).
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.
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.
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.
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.
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.
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.
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.

Precompiled headers, re-including files and Intellisense

I have a precompiled header that contains includes for various 3rd party libraries, e.g.:
#ifndef PRECOMPILED_H
#define PRECOMPILED_H
#include "booststuff.h"
#include "luastuff.h"
#endif
Where booststuff.h and luastuff.h are header files in my project that just include various boost / lua related things and set up some typedefs / usings / namespace aliases.
I set up the precompiled header in the usual way inside visual studio (2012), and use the force include option to include it in every cpp file.
In the cpp files, I've also been fairly careful to #include "booststuff.h" where I actually use it as well (I sometimes disable precompiled headers to test this). However, I've been wondering lately whether that's a good idea. So:
Does anything bad happen if I include a file again that's already included in the precompiled header (I don't see why it would, but I've seen things about headers having to be included "in the same order", and not really understood what they were on about)?
Does it affect Intellisense (unusably slow with a fairly small project)? I'd be happy to give up some portability for better Intellisense since I currently have no desire to switch platforms.
If each include file has #pragma once in it, the compiler will completely skip reading the file on the second and subsequent attempts to include it. It isn't stated explicitly but I assume the precompiled header tracks this information as well.

Organize includes

Is there some preferred way to organize ones include directives?
Is it better to include the files you need in the .cpp file instead of the .h file? Are the translation units affected somehow?
How about if I need it in both the .h file and .cpp file, should I just include it in the .h file? Will it matter?
Is it a good practice to keep the already defined files in a precompiled header (stdafx.h), for instance std and third party libraries? How about my own files, should I include them in a stdafx.h file along the way as I create them?
// myClass.h
#include <string>
// ^-------- should I include it here? --------
class myClass{
myClass();
~myClass();
int calculation()
};
// myClass.cpp
#include "myClass.h"
#include <string>
// ^-------- or maybe here? --------
[..]
int myClass::calculation(){
std::string someString = "Hello World";
return someString.length();
}
// stdafx.h
#include <string.h>
// ^--------- or perhaps here, and then include stdafx.h everywhere? -------
You should have them at the top of the file, all in one place. This is what everyone expects. Also, it is useful to have them grouped, e.g. first all standard headers, then 3rd-party headers (grouped by library), then your own headers. Keep this order consistent throughout the project. It makes it easier to understand dependencies. As #James Kanze points out, it is also useful to put the header that declares the content first. This way you make sure that it works if included first (meaning it does no depend on any includes that it does not include itself).
Keep the scope as small as possible, so that a change in the header affects the least number of translation-units. This means, whenever possible include it in the cpp-file only. As #Pedro d'Aquino commented, you can reduce the number of includes in a header by using forward declarations whenever possible (basically whenever you only use references or pointers to a given type).
Both - explicit is better than implicit.
After some reading, I believe you should only include headers in the PCH if you are confident that they do not change anymore. This goes for all standard headers as well as (probably) third party libraries. For your own libraries, you be the judge.
This article on Header file include patterns should be helpful for you.
Is there some preferred way to organize ones include directives?
Yes, you can find them in the above article.
Is it better to include the files you need in the .cpp file instead of
the .h file? Are the translation units
affected somehow?
Yes, it is better to have them in .cpp. Even, if a defined type is required in definition of another type, you can use forward declaration.
How about if I need it in both the .h file and .cpp file, should I just
include it in the .h file? Will it
matter?
Only in .h file, but it is suggested to forward declare in header files, and include in .cpp files.
Is it a good practice to keep the already defined files in a precompiled
header (stdafx.h), for instance std
and third party libraries? How about
my own files, should I include them in
a stdafx.h file along the way as I
create them?
I personally have not used precompiled headers, but there has been a discussion on them on Stackoverflow earlier:
Precompiled Headers? Do we really need them
Is there some preferred way to organize ones include directives?
No common conventions. Some suggest alphabet-sorting them, I personally dislike it and prefer keeping them logically grouped.
Is it better to include the files you need in the .cpp file instead of the .h file?
In general, yes. It reduces the count of times that the compiler needs to open and read the header file just to see the include guards there. That may reduce overall compilation time.
Sometimes it's also recommended to forward-declare as much classes as possible in the headers and actually include them only in .cpp's, for the same reason. The "Qt people" do so, for example.
Are the translation units affected somehow?
In semantic sense, no.
How about if I need it in both the .h file and .cpp file, should I just include it in the .h file? Will it matter?
Just include it in the header.
Is it a good practice to keep the already defined files in a precompiled header (stdafx.h), for instance std and third party libraries? How about my own files, should I include them in a stdafx.h file along the way as I create them?
Precompiled headers can significantly reduce compilation times. For example: one of my projects that includes boost::spirit::qi compiles in 20 secs with PCH on, and 80 secs — without. In general, if you use some heavily template-stuffed library like boost, you'd want to utilise the advantage of PCH.
As for the question in your code sample: since you don't use std::string in the header, it's better to include it in the .cpp file. It's alright to #include <string> in stdafx.h too — but that will just add a little bit of complexity to your project and you'll hardly notice any compilation speed-up.
(4) I wouldn't recommend to include any additional files into stdafx.h. or similar "include_first.h" files. Direct including into cpp or particular h files allow you to express dependencies of your code explicitly and exclude redundant dependencies. It is especialy helpful when you decide to decompose monolithic code into a few libs or dll's. Personally, I use files like "include_first.h" (stdafx.h) for configuration purpose only (this file contains only macro definitions for current application configuration).
It is possible to provide precompiled headers for your own files by marking another file to stop precompilation instead of stdafx.h (for instance, you can use special empty file named like "stop_pch.h").
Note, precompiled headers may not work properly for some kinds of sofisticated usage of the preprocessor (particulary, for some technics used in BOOST_PP_* )
From the performance point of view:
Changing any of the headers included from stdafx.h will trigger a new precompilation, so it depends on how "frozen" the code is. External libraries are typical candidates for stdafx.h inclusion, but you can certainly include your own libraries as well - it's a tradeoff based on how often you expect to change them.
Also, with the Microsoft compiler you can put this at the top of each header file:
#pragma once
This allows the compiler to fully skip that file after the first occurrence, saving I/O operations. The traditional ifndef/define/endif pattern requires opening and parsing the file every time it's included, which of course takes some time. It can certainly accumulate and get noticeable!
(Make sure to leave the traditional guards in there, for portability.)
It might be important to notice that the order of classes in Translation Unit need to be correct or some c++ features are just disabled and results in a compile-time error.
Edit: Adding examples:
class A { };
class B { A a; }; // order of classes need to be correct

Deciding which standard header files to #include

Suppose i am editing some large C++ source file, and i add a few lines of code that happen to use auto_ptr, like in the following example.
#include <string>
// ... (much code here)
void do_stuff()
{
std::string str("hello world");
// ... (much code here too)
std::auto_ptr<int> dummy; // MY NEW CODE
// ...
}
This example compiles on gcc 3.4.4 (cygwin), because the standard header <string> happens to include the header <memory> needed for compilation of auto_ptr. However, this doesn't work on gcc 4.5.0 (mingw); they seem to have cleaned up their header files or something.
So, when i add code that uses auto_ptr, should i immediately go look whether the file contains #include <memory> at the beginning, as this answer implies? I never do it (i find it too annoying); i always rely on the compiler to check whether any #include is missing.
Is there any option that would not be disruptive to coding, and would ensure portability of my code?
Is there a C++ standard library implementation whose headers don't include each other more than is required?
If you use something in the standard library, you should include the header in which it is defined. That is the only portable option. That way you avoid the instance you cite where one header happens to include another in one version or compiler, but not another. auto_ptr is defined in <memory>, so if you use it, include that header.
[edit...]
In answer to your comment... Are you asking if the compiler can help detect when you use something from a standard header you didn't directly include? This would be helpful, but I think it's a little too much to ask. This would require the compiler to know which standard library headers contain which standard library definitions, and then check that you included the right ones for the definitions you used.
Determining exactly how a header was included is also a tall task. If you are using a standard library definition, then you must be including the header somehow. The compiler would have to tell whether you included the header yourself (possibly through headers of your own or a third-party library) or whether it came through another standard library header. (For instance, in your example, it would have to be able to tell the difference between <memory> being included via <string> or being included within your own code.)
It would have to handle different version of the standard library (e.g. C++03 vs C++0x) and different vendors. And what if those vendors of a third-party stdlib do not exactly follow the standard, then you could get bad warnings about which headers to include.
I'm only saying this to try to explain (with my limited compiler/stdlib knowledge) why I don't think compilers have this feature. I do agree, it would be helpful, but I think the cost outweighs the benefit.
The best way is to include the correct header in which the construct is defined.
and Include files should protect against multiple inclusion through the use of macros that "guard" the files
Generally header files have "include guards" surrounding them. The guards are formed by:
MyHeader.h:
#ifndef __MY_HEADER_H__
# define __MY_HEADER_H__
//body of MyHeader.h
#endif
So, you could include MyHeader.h as many times as you want:
#include "MyHeader.h"
#include "MyHeader.h"
#include "MyHeader.h"
#include "MyHeader.h"
And it won't cause any problems for the compiler (it will only ever be included once). Moreover you could include another file that includes "MyHeader.h", and the same rule would apply.
What this means is, if you ever want to use something that is defined in a header - include it! (Even if you think something else might include it, there is no reason not to be safe).

C++ Header order [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
What order should headers be declared in a header / cpp file? Obviously those that are required by subsequent headers should be earlier and class specific headers should be in cpp scope not header scope, but is there a set order convention / best practice?
In a header file you have to include ALL the headers to make it compilable. And don't forget to use forward declarations instead of some headers.
In a source file:
corresponded header file
necessary project headers
3rd party libraries headers
standard libraries headers
system headers
In that order you will not miss any of your header files that forgot to include libraries by their own.
Good practice: every .h file should have a .cpp that includes that .h first before anything else. This proves that any .h file can be put first.
Even if the header requires no implementation, you make a .cpp that just includes that .h file and nothing else.
This then means that you can answer your question any way you like. It doesn't matter what order you include them in.
For further great tips, try this book: Large-Scale C++ Software Design - it's a shame it's so expensive, but it is practically a survival guide for C++ source code layout.
In header files, I tend to put standard headers first, then my own headers (both lists being ordered alphabetically). In implementation files, I put first the header corresponding (if any), then standards headers and other dependency headers.
Order is of little importance, except if you make a great use of macros and #define ; in that case, you must checked that a macro you defined doesn't replace a previously included one (except if that's what you want, of course).
Concerning this statement
those that are required by subsequent headers should be earlier
A header shouldn't rely on other headers being included before it! If it requires headers, it just includes them. Header guards will prevent multiple inclusion:
#ifndef FOO_HEADER_H
#define FOO_HEADER_H
...
#endif
EDIT
Since I wrote this answer, I changed my way of ordering the include directives in my code. Now, I try to always put headers in increasing order of standardization, so the headers of my project come first, followed by 3rd party libraries headers, followed by standard headers.
For instance, if one of my file uses a library I wrote, Qt, Boost and the standard library, I will order the includes as follow:
//foo.cpp
#include "foo.hpp"
#include <my_library.hpp>
// other headers related to my_library
#include <QtCore/qalgorithms.h>
// other Qt headers
#include <boost/format.hpp> // Boost is arguably more standard than Qt
// other boost headers
#include <algorithms>
// other standard algorithms
The reason why I do that is to detect missing dependencies in my own headers: let's assume for instance that my_library.hpp uses std::copy, but doesn't include <algorithm>. If I include it after <algorithm> in foo.cpp, this missing dependency will go unnoticed. On the contrary, with the order I just presented, the compiler will complain that std::copy has not been declared, allowing me to correct my_library.hpp.
In each "library" group, I try to keep the include directives ordered alphabetically, to find them more easily.
On a sidenote, a good practice is also to limit at a maximum the dependency between header files. Files should include as little headers as possible, especially headers file. Indeed, the more headers you include, the more code needs to be recompiled when something changes. A good way to limit these dependencies is to use forward declaration, which is very often sufficient in header files (see When can I use a forward declaration?).
Google C++ Style Guide, Names and Order of Includes :
In dir/foo.cc, whose main purpose is to implement or test the stuff in dir2/foo2.h, order your includes as follows:
dir2/foo2.h (preferred location — see details below).
C system files.
C++ system files.
Other libraries' .h files.
Your project's .h files.
I used to order them in alphabetical order (easier to find)
The "how" is not obvious, but the "what" is.
Your goal is to make sure that the order in which you include header files never matters (and i mean "NEVER !").
A good help is to test whether header files compile when building cpp files (one for each header file) that only include one of them.
For .cpp files, you should include the header of the class or whatever you are implementing first, so you catch the case where this header is missing some includes. After that, most coding guidelines tend to include system headers first, project headers second, for example the Google C++ Style Guide.
It's a dependency thing and it depends largely on what you put in our headers. A fact is that you can be really notorious about this and minimize to keep your includes strict but you'll eventually run into a scenario where you'll wanna use inclusion guards.
#ifndef MY_HEADER_H
#define MY_HEADER_H
//...
#endif
The problem isn't that apparent in the beginning, but as the complexity of your software grows so does your dependencies. You can do well, and be smart about it but larger C++ projects are generally riddled with includes. You can try, but you can only do so much. So be diligent and think about your includes, YES! But you'll most certainly have cyclic dependencies at some point and that is why you need inclusion guards.
If a header needs other headers then it just includes them in that header.
Try to structure your code so you pass pointers or references and forward declare where you can.
In the implementation then the header that defines it should be listed first (except in Visual Studio if you are using pch then stdafx would go first).
I generally list them as I need.
I've found the following convention the most useful:
module.cpp:
// this is the header used to trigger inclusion of precompiled headers
#include <precompiled.h>
// this ensures that anything that includes "module.h" works
#include "module.h"
// other headers, usually system headers, the project
The important thing is to put the module's header as the first non-precompiled header. This ensures "module.h" has no unexpected dependencies.
If you're working on a large project with slow disk access times, I've seen this style used to decrease build times:
module.cpp:
// this is the header used to trigger inclusion of precompiled headers
#include <precompiled.h>
// this ensures that anything that includes "module.h" works
#include "module.h"
// other headers, usually system headers, the project
#if !defined _OTHER_MODULE_GUARD_
#include "other_module.h"
#endif
#if !defined _ANOTHER_MODULE_GUARD_
#include "another_module.h"
#endif
It's a bit verbose but does save on disk seeking since the header won't be searched for / opened if it's already been included. Without the guard check, the compiler will seek for and open the header file, parse the whole file to end up #ifdefing the whole file out.