15

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?
YSC
  • 34,418
  • 7
  • 80
  • 129
dave
  • 1,660
  • 1
  • 7
  • 19
  • 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. – user7860670 Jan 25 '19 at 09:56
  • 7
    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. – StoryTeller - Unslander Monica Jan 25 '19 at 10:01
  • 1
    would your `.tpp` be included by others? if not (I guess), why guard over it? – apple apple Jan 25 '19 at 10:16
  • 1
    otherwise this may be used to optionally include feature `.tpp`s (by user), then the guard is needed (but I'd say it'd be better to use `.hpp`) – apple apple Jan 25 '19 at 10:19
  • plus I don't think anyone would directly include `.tpp`, just like `.cpp` – apple apple Jan 25 '19 at 10:23
  • You may be able to replace all these include guards with `#pragma once` now that it is widely supported. – quamrana Jan 25 '19 at 11:03
  • @quamrana [Guards are better than `#pragma once` in every way](https://stackoverflow.com/questions/1143936/pragma-once-vs-include-guards/34884735#34884735). There's no reason to put the non-standard version in new code. – Leushenko Jan 25 '19 at 15:32

2 Answers2

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.

YSC
  • 34,418
  • 7
  • 80
  • 129
  • 1
    Nice! Although if I prevent including the .tpp file directly by throwing this error, is the MYCLASS_TPP define not reduntant? – dave Jan 25 '19 at 10:24
  • 2
    @dave No. If your user first includes `myclass.hpp` and then `myclass.tpp`, the error won't fire. – Max Langhof Jan 25 '19 at 10:26
  • 1
    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. – francesco Jan 25 '19 at 10:43
  • 1
    @francesco There's always a way around, but its a bad way no-one should take: include guards are not needed: just terribly useful. – YSC Jan 25 '19 at 10:44
  • 2
    @francesco The hair-splitting answer would be "`#pragma once` can also do it in basically any compiler". – Max Langhof Jan 25 '19 at 10:45
  • @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. – Oliv Jan 25 '19 at 10:48
  • @Oliv `#pragma once`, while supported by all compilers in principle, nonetheless has [implementation-defined behavior](https://en.wikipedia.org/wiki/Pragma_once#Caveats), 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.) – Arne Vogel Jan 28 '19 at 10:35
  • @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](https://docs.microsoft.com/en-us/cpp/preprocessor/once?view=vs-2017) For Gcc [link](https://gcc.gnu.org/onlinedocs/cpp/Pragmas.html). For Clang see Gcc (clang still not has its own complete documentation!). According to [wikipedia](https://en.wikipedia.org/wiki/Pragma_once) only Cray still not has implemented pragma once. If one target Cray the code will certainly not be portable whatsoever. – Oliv Jan 28 '19 at 14:59
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.

Oliv
  • 16,492
  • 1
  • 24
  • 63
  • 2
    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. – YSC Jan 25 '19 at 12:09
  • @YSC 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. – Oliv Jan 25 '19 at 12:21
  • I was thinking about compilers too old/obscure to know `#pragma once` ;) But yes. – YSC Jan 25 '19 at 12:22
  • 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. – Francis Cugler Jan 25 '19 at 14:32