Template (.tpp) file include guards

Do I need include guards in the .tpp file or is it sufficient to have them in the .hpp file?

Include guards are never needed: they're just terribly useful, cheap, non-disruptive and expected. So Yes, you should protect both files with header guards:

  • Terribly useful: they allow you to declare a dependency from multiple files without keeping track of which files have already been included.
  • Cheap: this is just some precompilation tokens.
  • Non-disruptive: they fit well with most use-cases of #include (I've had a colleague who didn't know how to write macros so he #included implementation files facepalm).
  • Expected: developers know what they are and barely notice them; on the contrary a header file missing include guards wakes us up and adds to the global wtf/line counter.

I take the opportunity to highlight the comment from StoryTeller:

I'd go a step further and add a descriptive #error directive if the hpp guard is not defined. Just to offer a little protection from people including the tpp first.

Which will translate to:

#ifndef MYCLASS_TPP
#define MYCLASS_TPP

#ifndef MYCLASS_HPP
#error __FILE__ should only be included from myclass.hpp.
#endif // MYCLASS_HPP

template<typename T>
T MyClass<T>::foo(T obj)
{
    return obj;
}

#endif // MYCLASS_TPP

Notice: if a translation unit first #include <myclass.hpp> and then #include <myclass.tpp>, no error is fired and everything is fine.


Just use pragma once in all headers file. The compiler will ensure your file will be included only once. The compiler may only fail to recognize in very unreasonable condition: someone structure its include directories using hard-link. Who does this? If someone cannot find a unique name for its file, why would he be more skilled to find a unique name for each include guard for all the header files?

On the other hand, include guard may be broken because the name of the macro will not be that unique, because of a copy/paste, or a header file created by first copying an other, etc...

How are chosen the unique macro name: <project name>_<filename>? How could it be more unique than a uniqueness based on the entire root directory structure?

So in the end, one should consider when choosing between include guard or pragma once, the cost of the job that is necessary to ensure uniqueness:

1 - For pragma once you only have to ensure that the directory structured of your system is not messed-out thanks to hard links.

2 - For include guard for each file on your system you should ensure that the macro name is unique.

I mean as a manager, evaluating the cost of this job and the failure risk does let only one option. Include guard are used only when no evaluation is performed: it is a non decision.