3 ms·
Good stuff, if slightly self-contradictory in places. The header file named after the source should be included first (to catch errors in the header) and the he
by JonChesterfield 3y ago
Good stuff, if slightly self-contradictory in places. The header file named after the source should be included first (to catch errors in the header) and the header file defining various macros should be included first (as otherwise it doesn't work).
The detect-missing-includes-in-header is better handled by a separate compilation job which compiles the header by itself as it if was C++, `clang -xc foo.h`, solely for the purpose of catching that error. Then the include your own header first rule no longer matters.
Forward declarations have a cost which the article misses. When the thing in question changes, your compiler no longer warns you when the forward declaration is out of sync with the real thing, and the linker diagnostics are usually less comprehensible. Also it's a nuisance to update all the forward declarations. An <iosfwd> style header, included at the top of the <ios> header, gives ~99% of the compile time advantage of forward declarations with none of the failure modes and usually less typing in the caller.
- mike_hock 3y agoIt basically consists of: 1) The basic, ubiquitous, and uncontroversial rule that headers should be self-contained, i.e. guarded and include their direct dependencies, and 2) nonsensical rules resulting from failure to follow the first rule, or failure to follow the other basic, ubiquitous and uncontroversial rule that source files should also include their direct dependencies. Manual forward declarations are a non-starter. Any header that contains a class declaration that it might ever make sense to refer to as an incomplete type (so, like, 100% of all classes, rounded to 3 decimal places) should have a corresponding iosfwd-style forward header. The common header is just another header. You include it if you need it and you don't if you don't.
- SAI_Peregrinus 3y agoExactly. If the order of your includes matters, you screwed up. Run "Include What You Use", fix the errors.
- mort96 3y agoThere's nothing self-contradictory. The two rules you're speaking of are: make sure that your header file is the first #include in the corresponding source file, except the common header, if your codebase has one. and: make sure that each source file includes the common header before everything else This defines a pretty clear order: 1) common header, if it exists; 2) the corresponding header for the source file, if it exists; 3) other headers needed by the source file.
- JonChesterfield 3y agoAh you are right, I missed the "except the common header" clause. Probably because the preceding part was in bold, possibly because "common header" is defined further down the article so the clause didn't mean much when first read.