Don’t Put All Includes in the .hxx


Ok, one more thing about headers, then I promise to talk about something else.

Just because a header file is called a header file, you shouldn’t include all your headers there. Often, a source file, where the definition of you functions and/or classes are, need quite a lot of headers to do its work. It might for instance need <algorithm> to do some sorting or searching, a fact your declarations don’t need to worry about:

processing.hxx

#include "MyType.hxx"

void process(MyType obj); 

processing.cc

#include "processing.hxx"
#include <algorithm>

void process(MyType obj) {
    std::find(...);
    std::sort(...);
}

You almost always need to include some headers in the .hxx, so why not put them all there? While compiling your .cc file, it doesn’t really matter, since all those files are included anyway. But when someone else includes your header, they suddenly depend on everything your implementation depends on. This also adds to compilation time for your users. So do your includes as listed above, don’t move #include <algorithm> to the .hxx.

There. I promise to get my head out of the headers, if you promise to order your include directives the right way, dont use using in header files, and only include what's needed for the declarations in the header.

3 Responses to “Don’t Put All Includes in the .hxx”

  1. Another Reason to Avoid #includes in Headers « C++ on a Friday Says:

    […] have already argued that you shouldn’t put all your includes in your .h files. Here is one more reason, compilation […]

  2. How to avoid includes in headers « C++ on a Friday Says:

    […] Don't Put All Includes in the .hxx […]

  3. miglior seggiolino auto Says:

    Hiya very nice blog!! Man .. Beautiful .. Superb ..
    I’ll bookmark your web site and take the feeds also?
    I am satisfied to find a lot of useful information here in the publish,
    we’d like develop extra techniques in this regard, thank you for sharing.

    . . . . .


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s