Including Standard Library Headers Once in C++

ccode-quality

I am writing a program with multiple headers and code files, as so:

  • message.h
  • message.cpp
  • option.h
  • option.cpp
  • main.cpp

message.h includes option.h as message.cpp requires the definition of the class defined therein.

There are quite a few other files, however just to keep it brief…
If I want to call a function such as memcpy, I include string.h. I include string.h in message.h – so it works fine in message.cpp, but if I want to use it in option.cpp it gives me an error.

So I see two options:

  1. In option.h, I include message.h again. This should not be an issue as I have include guards in both header files, however I feel it's rather messy.
  2. I include string.h in option.h. Now I am including string.h in both of my header files.

This gives me the declaration for memcpy and so I can get on with my programming. However when I'm including 10 different headers for many different functions, it's going to be messy again.

What is a good way for me to structure my code to get around this issue, to keep my code as neat as possible? It has crossed my mind to make all my includes in one separate file and include that in all my header files, could this be a problem in the future, and is there a better way I can go about this to ensure my code is maintainable?

Best Answer

It's perfectly fine to #include additional headers in .cpp files that are not included in the corresponding .h. In fact, you should always do so if the header is not required in the .h, because that potentially speeds up compilation of anything that depends on your .h but not on your .cpp. See this classic Guru of the Week for some tips on minimizing unnecessary #includes in your header files (I don't think any of them have gone out of date yet).

In general, you should avoid relying on what other files do or don't include as much as possible, since that makes your code more modular (and more portable to other standard libraries). That means every file should explicitly and directly #include every header that it needs to know about (I'm assuming every header file has #include guards or an equivalent like #pragma once, since not having those is a far bigger problem). If the message.h author decides to follow that GotW I linked and cut down their superfluous #includes, it would be awfully frustrating if he unknowingly broke option.h/.cpp in the process. At work we once discovered some of our code would compile under GCC but not Clang solely because we were missing a few standard library #includes, and thus unknowingly depended on the fact that certain GCC headers #included each other.

So the direct answer to your original question is: You should directly include string.h in every file you plan on using it, and no others. Assuming you aren't using memcpy() inside option.h (that seems unlikely), that means the #include belongs in option.cpp.

Related Topic