Are Include Guards Necessary for Headers with Only Declarations?

cheaders

Consider the following assumptions about C programming (some of which go too far, I confess):

  • Putting any variable definitions in a header file is incorrect, because each translation unit creates its own copy of the data. And if it's extern and used from more than one place, we get UB. The correct usage is to declare variables in header files and define them in the corresponding implementation files.

  • Macros are bad form and can usually be converted to variables or functions.

  • Redeclaration of functions is completely legal.

PROVIDED the above is followed, include guards become unnecessary. There is an exception for inline functions, which have to be defined in the header, but many projects do not use them.

Given all of that, why is the include guard an industry standard? Most IDEs even add them automatically upon file creation.

Best Answer

In many (most?) non-trivial projects, header files contain typedef declarations or struct definitions. Neither of these are allowed to be repeated in a single translation unit (pre-processed source file).

As there are non-repeatable elements that are commonly placed in header files, and those elements also belong in a header file, it has become automatic for C (and C++) programmers to put include guards in their headers.

In C++, it is even more common, as inline functions are used much more and class definitions have the same restriction as struct definitions that they can't be repeated.

Related Topic