Search code examples
c++compilationheader-files

Should my header files be able to compile on their own?


A colleague recently claimed that header files should always be able to compile on their own (e.g. calling g++ someHeader.hpp should result in someHeader.hpp.gch without failure).

Is this statement "true"?

Is it a good/common practice to check if your headers are able to compile on their own?

If yes, what would be the advantage of such a test?

To me, this seems counterintuitive, since headers are included by the preprocessor in the compilation unit and only have to compile in the context of that unit.


Solution

  • Is it a good/common practice to check if your headers are able to compile on their own?

    Yes. The practice is good and as far as I know, common.

    If yes, what would be the advantage

    A header that doesn't work by itself must necessarily rely on the context where it is going to be included. Having a header work only when included into certain context is fragile. Fragility is a code smell.

    ... headers are included by the preprocessor in the compilation unit and only have to compile in the context of that unit.

    ... And also every other unit where the header is included into. Including those units that have not been written yet. And it should also keep working when changes are made to those units.

    A header that only works in a single translation unit at one point in time is not a very useful header in the long term.