Search code examples
c++includestandardsguard

C++ Include Structure


I was wondering what standards one should follow when including header files. Is it a good practice to re-include header files in relevant places provided those places use such header files? For example,

Say you have a main.cpp class that includes iostream and a custom class "myclass.h", because you use both std::ostream and an instance of myclass in your main.

Now, in your "myclass.h" you also include iostream because within your class you use std::ostream.

If you look back now, main is technically including iostream twice, because it includes it in itself, and it is also included in "myclass" (which main includes). I could think of a good reason to have this, and a bad reason, and I was wondering which is the correct way of going about this.

  1. Keep both includes and let the include guards do their job. If you ever change your implementation in "myclass" and remove the iostream include, your main will not break, because it includes iostream explicitly.
  2. Keep only the include in your "myclass" and remove it from main, as to have a single iostream include (and improve compilation time?), fix any errors that come up if you ever change your implementation in "myclass" and remove the iostream include as they come up.

I am leaning more towards the first solution, but again, I do not know C++ standards so well yet. Thanks, -Francisco


Solution

  • Keep the includes in both files and let the include guards do their job.

    If you depend on "indirect" includes it can be a pain with errors if you later change your "myclass.h" and wonder why your std::ostream won't work anymore in main.cpp. Also it might be confusing for others