Template (.tpp) file include guards
Asked Answered
L

2

16

When writing templated classes, I like to move the implementation into a different file (myclass.tpp) and include it at the bottom of the main header (myclass.hpp).

My Question is: do I need include guards in the .tpp file or is it sufficient to have them in the .hpp file?

Example code:

myclass.hpp

#ifndef MYCLASS_HPP
#define MYCLASS_HPP

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

//include template implemetation
#include "myclass.tpp"

#endif

myclass.tpp

#ifndef MYCLASS_TPP //needed?
#define MYCLASS_TPP //needed?

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

#endif //needed?
Lobectomy answered 25/1, 2019 at 9:54 Comment(7)
They should be present in all header files that are not supposed to be inlined multiple times. If myclass.tpp is supposed to be included only in myclass.hpp then it would make sense to add additional guards.Sitzmark
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.Foreboding
would your .tpp be included by others? if not (I guess), why guard over it?Notarize
otherwise this may be used to optionally include feature .tpps (by user), then the guard is needed (but I'd say it'd be better to use .hpp)Notarize
plus I don't think anyone would directly include .tpp, just like .cppNotarize
You may be able to replace all these include guards with #pragma once now that it is widely supported.Pharmacist
@Pharmacist Guards are better than #pragma once in every way. There's no reason to put the non-standard version in new code.Pigeonhole
T
16

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.

Tula answered 25/1, 2019 at 10:20 Comment(8)
Nice! Although if I prevent including the .tpp file directly by throwing this error, is the MYCLASS_TPP define not reduntant?Lobectomy
@dave No. If your user first includes myclass.hpp and then myclass.tpp, the error won't fire.Poorly
I disagree with the sentence include guards are never needed. Suppose an header A.hpp needs to include another header B.hpp (because, for instance, it uses the definitions found in B.hpp), and suppose you write a code which needs both A.hpp and B.hpp. Unless you inspect the code of A.hpp, you would not know that #include "B.hpp" is not needed. Then, you would include both A.hpp and B.hpp, resulting in a double include of B.hpp. The include guard prevents this.Sodomy
@Sodomy There's always a way around, but its a bad way no-one should take: include guards are not needed: just terribly useful.Tula
@Sodomy The hair-splitting answer would be "#pragma once can also do it in basically any compiler".Poorly
@MaxLanghof This urban legend that include guards are safer than pragma once should be destroyed once and for all. All the argument that applies against pragma once does apply to include guards. In the end I prefer when a systematic process is ensured by a machine than by a human.Uranography
@Uranography #pragma once, while supported by all compilers in principle, nonetheless has implementation-defined behavior, and does not work in all build setups. (If it works for you, that's fine, but that's only your personal preference. Also, I'm not even that sure about implementation-defined because it requires that the behavior is documented.)Fiche
@ArneVogel On this MSVC page, pragma once is recommended *It is not part of the C++ Standard, but it is implemented portably by several common compilers.*link For Gcc link. For Clang see Gcc (clang still not has its own complete documentation!). According to wikipedia only Cray still not has implemented pragma once. If one target Cray the code will certainly not be portable whatsoever.Uranography
U
3

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.

Uranography answered 25/1, 2019 at 11:10 Comment(4)
I agree: if you control your build environment (e.g. this is a proprietary project) there's no reason not to use #pragma once. If you're writing an open source library you'd like to be used on obscures build environments (embedded, old systems, etc.), maybe just stick to include guards.Tula
@Tula Not writing but maintaining an old library. For a new library, that may be added to an old system, you just specify that this library should not be hardlinked and that all. There are no reason to make every body pay for an ancient practice that might still be in use by a number of people that can be count on the one hand. It is like asking million of coder to loose their time to improbably increase the productivity of 2 or 3 system administrator.Uranography
I was thinking about compilers too old/obscure to know #pragma once ;) But yes.Tula
I believe they both have their uses. Years ago not all compilers supported #pragma once, so many were forced to use header guards, however, most compilers today should fully support #pragma once without issue. Typically if I have a single header file that is a class' declaration I'll use header guards with the name of the class file where that class file is the name of the class. If I have a header file that has a bunch of macros, defines, constants and just stand alone function declarations, then I'll more than likely use #pragma once. This is just my preference.Majors

© 2022 - 2024 — McMap. All rights reserved.