Search code examples
c++coding-style

Why not include all the standard headers always?


I am reading Herb Sutter's More Exceptional C++ and item 37 on forward declarations says:

Never #include a header when a forward declaration will suffice. Prefer to #include only <iosfwd> when the complete definition of a stream is not needed.

Also I heard plenty of advice on including only the headers needed by the compilation unit to reduce dependencies.

I understand perfectly well why this should apply to project headers, but I do not quite understand why is it bad to include unnecessary standard headers.

For example I do something like this:

//standard_library.h

#ifndef STANDARD_LIBRARY
#define STANDARD_LIBRARY

#include <iostream>
#include <chrono>
#include <thread>
...
// Everything I need in the project
#endif

and include this single header everywhere, where I need something from std

The problems that I can imagine are:

  1. Pollution of namespace by C library functions that do not need to be in the std namespace.
  2. Slower compilation time

But I haven't had significant problems with 1. sofar. Almost everything is in the std namespace. Also I do not fully understand why 2. is necessarily a significant problem. The standard headers rarely change. Also as far as I know the compiler can precompile them. When it comes to templates, they are instantiated(compiled) only when I need them.

There are also benefits:

  1. Less typing
  2. Less reading
  3. Less figuring out which headers I need and in which header a certain function is

I am a beginner programer without experience on big projects and I sincerely want to figure this out so please have mercy upon me.


Solution

  • Besides

    • namespace pollution
    • compilation time (although reducable by precompiled headers, it will hurt those compiling a large project once because they actually want to use it, and not develop - also you want to think about rebuilds which are necessary once in a while)

    you named "Less figuring out which headers I need and in which header a certain function is" as a benefit. I agree so far as this can be true for well designed libraries and headers.

    In practice however I experienced (at least with MFC/ATL) some errors which could be solved by figuring out the correct order of includes. On the other hand one day you want to resolve an issue which makes you travel across the included headers - now imagine yourself looking at tons of headerfiles actually having nothing to do with your code file.

    My conclusion is: The time you save by including a bunch of unnecessary headers do not pay off if you have to maintain a large project later on. The more time you invest before starting including any headers, the more time you will safe afterwards - but mostly without actually recognizing it.