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.
A header file is a file with extension . h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler.
Some general guidelines:
foo.cxx
, everything defined in there had better be declared in foo.h
.#include
s whenever possible. This allows you to break the cyclic header dependencies. Essentially, for cyclical dependencies across separate files, you want a file-dependency graph that looks something like this:
A.cxx
requires A.h
and B.h
B.cxx
requires A.h
and B.h
A.h
requires B.h
B.h
is independent (and forward-declares classes defined in A.h
)If your code is intended to be a library consumed by other developers, there are some additional steps that are important to take:
include/
and src/
subdirectories in my C or C++ projects, where include/
has all of my public headers, and src/
has all of my sources. and private headers.I'd recommend finding a copy of John Lakos' book Large-Scale C++ Software Design. It's a pretty hefty book, but if you just skim through some of his discussions on physical architecture, you'll learn a lot.
Check out the C and C++ coding standards at the NASA Goddard Space Flight Center. The one rule that I specially noted in the C standard and have adopted in my own code is the one that enforces the 'standalone' nature of header files. In the implementation file xxx.cpp for the header xxx.h, ensure that xxx.h is the first header included. If the header is not self-contained at any time, then compilation will fail. It is a beautifully simple and effective rule.
The only time it fails you is if you port between machines, and the xxx.h header includes, say, <pqr.h>
, but <pqr.h>
requires facilities that happen to be made available by a header <abc.h>
on the original platform (so <pqr.h>
includes <abc.h>
), but the facilities are not made available by <abc.h>
on the other platform (they are in def.h
instead, but <pqr.h>
does not include <def.h>
). This isn't a fault of the rule, and the problem is more easily diagnosed and fixed if you follow the rule.
Check the header file section in Google style guide
Tom's answer is an excellent one!
Only thing I'd add is to never have "using declarations" in header files. They should only be allowed in implementation files, e.g. foo.cpp
.
The logic for this is well described in the excellent book "Accelerated C++" (Amazon link - sanitised for script kiddie link nazis)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With