Search code examples
c++cdependenciesincludedependency-management

Is it common practive to #include header files already included by included header files?


Let's say we have a header file A.h which depends on things declared in B.h and C.h. B.h also depends an C.h and therefore includes it. In this case we don't need to include C.h in A.h and it will compile just fine without it.

But I am wondering what the best course of action is in these cases. If B.h somehow changes and no longer depends on C.h, A.h will break.

On the other hand if I think this through to the end it seems unneccessary/impractical to reinclude every single dependency.

A common case I have are standard libraries. In almost all my header files I would have to include <stdint.h> and <stdbool.h>. I often skip this because they were already included in one of the dependencies but this always feels kind of arbitrary.


Solution

  • If B.h somehow changes and no longer depends on C.h, A.h will break.

    Exactly. Why take the chance?

    On the other hand if I think this through to the end it seems unneccessary/impractical to reinclude every single dependency.

    If it's impractical, your file has too many dependencies and is probably too large.

    Refactor it into smaller modules.

    A common case I have are standard libraries. In almost all my header files I would have to include <stdint.h> and <stdbool.h>. I often skip this because they were already included in one of the dependencies but this always feels kind of arbitrary.

    I admit to sometimes skipping these when I know one of my headers — expressly defined to bring the types I need into scope — has done this. It's unlikely to be refactored because it has these headers for this reason, not for some other dependency that may disappear.

    But, ultimately, there's nothing wrong with including <stdint.h> and <stdbool.h> where you need it. I'm surprised that you find you need them in "almost all [your] header files", to be honest.