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?
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.
Related
I have gotten to a point in my course where they use Code::Blocks to automatically make a header file. However, I don't think it's necessary to download Code::Blocks specifically for this reason, and so I am looking for a way to make my own header files.
And so, I started my search online to find out exactly how to do this.
I checked How to create my own header file in c++? [closed] and also cplusplus.com
However, the former uses uses #ifndef YOUR_NAME_INCLUDE and #define YOUR_NAME_INCLUDE whereas the latter uses #ifndef __X_H_INCLUDED__ and #define __X_H_INCLUDED__, with 2 underscores surrounding the #ifndef and #define. How should I format my header guards? Does it really matter?
For example, if I have a file foo.h, which looks like this:
#ifndef ???
#define ???
int sum(int a, int b) {
return a + b;
}
#endif
should I put SUM_INCLUDED, FOO_INCLUDED, FOO_H instead of the ??? or something else altogether?
Second, is making a header file really as easy as just sticking a .h or .hpp to the end of it?
#ifndef FOO
#define FOO
struct foo {};
#endif
The above canonical example ensures that the contents (between #ifndef FOO and #define FOO) are compiled only once allowing us to include this file (say foo.h) in multiple compilation units without causing struct foo to be multiply defined.
There really isn't any "magic" about an include file other than this. In fact, the extension doesn't even matter. It could be foo.h or foo.hh or just foo (like the standard library headers like vector or iostream).
Ultimately, it's personal preference how you structure your include guards. Some use __FOO__ (note this runs afoul of C++ standard regarding reserved identifiers) or FOO_H_INCLUDED (which is standard compliant) while others may elect for different patterns.
While it's not strictly standard C++, my team uses #pragma once and foregoes the ifndef/define/endif code. It's supported by all the compilers we use (gcc/msvc/clang) and you don't have drawbacks such as too different foo.h files causing one (or the other) definition to be excluded.
The same file then looks like this
#pragma once
struct foo {};
So I know how to place an include guard in my own header files with the standard
#ifndef ...
#define ...
Now, My question is about including libraries that are not my own. would be a good example. I have a header file which requires the use of string, so I do the following
foo.h
#ifndef FOO_H
#define FOO_H
#include <string>
... code etc ...
#endif
Now, if I have another header file called.. lets say, bar.h, which ALSO requires the use of <string>, how can i prevent multiple inclusions? Does the STL already have include guards in place?
The STL library also has include guards and any good library should do the same.
#ifndef _GLIBCXX_STRING
#define _GLIBCXX_STRING 1
This is from gcc's
Assuming that by "STL" you mean the C++ standard library, then you can refer to the C++ standard. ยง17.6.2.2/2 states:
A translation unit may include library headers in any order. Each may be included more than once, with no effect different from being included exactly once, except that the effect of including either <cassert> or <assert.h> depends each time on the lexically current definition of NDEBUG.
This means that it is not necessary to guard against multiple inclusions of the same header.
Include guard use to guard the content inside the guard pair. You can check the system head file string, it also has the include guard. So, don't worry about multiple inclusions.
I have 3 classes (it could be 300) , each one with its own header and implementation.
I'd like to write an 'elegant' way to organize the way I load of any class needed by every class of the three. Maybe this example helps...
I have : class1 class2 class3
Every header has:
#ifndef CLASS#_H
#define CLASS#_H
#define FORWARD_STYLE
#include "general.h"
#endif
Every implementation has:
#define DIRECT_STYLE
#include "general.h"
OK
I'm going to write a 'general.h' file in which I'd have :
#ifndef DIRECT_STYLE
#ifndef CLASS1_H
#include "class1.h"
#endif
#ifndef CLASS2_H
#include "class2.h"
#endif
#ifndef CLASS3_H
#include "class3.h"
#endif
#endif
#ifndef FORWARD_STYLE
class Class1;
class Class2;
class Class3;
#endif
// a lot of other elements needed
#include <string.h>
#include <stdio.h"
....
#include <vector.h"
( all the class I need now and in the future )
This is a good structure ? Or I'm doing some idiot thing ?
My goal is having one unique 'general.h' file to write all the elemenst I need...
Are this to work fine ?
Thanks
The basic rules to follow are:
Let each of your source file include all the header files it needs for getting compiled in a standalone manner. Avoid letting the header files include in the source file indirectly through other files.
If you have constructs which will be needed across most source files then put them in a common header and include the header in Only in those source files which need it.
Use Forward declarations wherever you can.There are several restrictions of when you can get away using them,read this to know more about those scenarios.
Overall it is a good idea to avoid including unnecessary code in source files through a common header because it just results in code bloat, so try and keep it to a minimum. Including a header just actually copy pastes the entire header to your source file and Including unnecessary files has several disadvantages, namely:
Increase in compilation time
Pollution of global namespace.
Potential clash of preprocessor names.
Increase in Binary size(in some cases though not always)
This might like a fine idea now, but won't scale and should be avoided. Your general.h file will include a vast amount of files, and thus all files that include it will (a) take ages to compile or not compile at all due to memory restrictions and (b) will have to be re-compiled every time anything changes.
Directly include the headers you need in each file, and define a few forward declaration files, and you should be fine.
The #define in a header will probably be ok, but it can propagate through lots of sources and potentially cause problems. More seriously, any time general.h or any of its includes change your entire project rebuilds. For small projects this isn't an issue, for larger projects it will result in unacceptable build times.
Instead, I utilize a few guidelines:
In headers, forward declare what you can, either explicitly or with #include "blah_fwd.h" as seen in the standard library.
All headers should be able to compile on their own and not rely on the source file including something earlier. This can be easily detected by all source files always including their own header first.
In source files, include what you need (usually you can't get away with forward declarations in source files).
Also note to never use using in headers because it will pollute the global namespace.
If this seems like a lot of work, unfortunately that's because it is. This is a system inherited from C and requires some level of programmer maintenance. If you want to be able to decide at a high level what's used by your project and let the compiler/runtime figure it out, perhaps C++ isn't the right language for your project.
In eclipse, whenever I create a new C++ class, or C header file, I get the following type of structure. Say I create header file example.h, I get this:
/*Comments*/
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
/* Place to put all of my definitions etc. */
#endif
I think ifndef is saying that if EXAMPLE_H_ isn't defined, define it, which may be useful depending on what tool you are using to compile and link your project. However, I have two questions:
Is this fairly common? I don't see it too often. And is it a good idea to use that rubric, or should you just jump right into defining your code.
What is EXAMPLE_H_ exactly? Why not example.h, or just example? Is there anything special about that, or could is just be an artifact of how eclipse prefers to auto-build projects?
This is a common construct. The intent is to include the contents of the header file in the translation unit only once, even if the physical header file is included more than once. This can happen, for example, if you include the header directly in your source file, and it's also indirectly included via another header.
Putting the #ifndef wrapper around the contents means the compiler only parses the header's contents once, and avoids redefinition errors.
Some compilers allow "#pragma once" to do the same thing, but the #ifndef construct works everywhere.
This is just a common way to protect your includes - in this way it prevents the code from being included twice. And the identifier used could be anything, it's just convention to do it the way described.
Is it common? Yes - all C and C++ header files should be structured like this. EXAMPLE_H is a header guard, it prevents the code in the header being included more than once in the same translation unit, which would result in multiple definition errors. The name EXAPMLE_H is chosen to match the name of the header file it is guarding - it needs to be unique in your project and maybe globally as well. To try to ensure this, it's normal to prefix or suffix it with your project name:
#define MYPROJ_EXAMPLE_H
for example, if your project is called "myproj". Don't be tempted into thinking that prefixing with underscores will magically make it unique, by the way - names like _EXAMPLE_H_ and __EXAMPLE_H__ are illegal as they are reserved for the language implementation.
Always do this at the top of a header file. It's typically called a header guard or an include guard.
What it does is make it so that if a header file would be included multiple times, it will only be included once. If you don't do it, then you'll end up with errors about things being defined multiple times and things like that.
The exact define doesn't matter that much, though typically it's some variation on the file name. Basically, you're checking whether the given macro has been defined. If it hasn't, then define it, and continue with including the file. If it has, then you must have included the file previously, and the rest of the file is ignored.
This is an include guard. It guarantees that a header is included no more than once.
For example, if you were to:
#include "example.h"
#include "example.h"
The first time the header is included, EXAMPLE_H_ would not be defined and the if-block would be entered. EXAMPLE_H_ is then defined by the #define directive, and the contents of the header are evaluated.
The second time the header is included, EXAMPLE_H_ is already defined, so the if-block is not re-entered.
This is essential to help ensure that you do not violate the one definition rule. If you define a class in a header that didn't have include guards and included that header twice, you would get compilation errors due to violating the one definition rule (the class would be defined twice).
While the example above is trivial and you can easily see that you include example.h twice, frequently headers include other headers and it's not so obvious.
Consider this
File foo.c:
#include foo.h
#include bar.h
File bar.h
#include <iostream>
#include foo.h
Now, when we compile foo.c, we have foo.h in there twice! We definitely don't want this, because all the functions will throw compile errors the second time around.
To prevent this, we put the INCLUDE GUARD at the top. That way, if it's already been included, we define a preprocessor variable to tell us not to include it again.
It's very common (often mandated), and very frustrating if someone doesn't put one in there. You should be able to simply expect that each .h file has a header guard when you included. Of course, you know what they say when you assume things ("makes an ass of u and me") but that should be something you're expecting to see.
This is called an include guard and is indeed a common idiom for C/C++ header files. This allows the header file to be included multiple times without multiply including its contents.
The name EXAMPLE_H_ is an arbitrary convention but has to obey naming rules for C preprocessor macros, which excludes names like example.h. Since C macros are all defined in a single global namespace, it is important that you do not have different header files that use the same name for their include guard. Therefore, it is usually a good idea to include the name of your project or library in the include guard name:
#ifndef __MYPROJECT_EXAMPLE_H__
...
I know it to prevent multiple inclusion of header file. But suppose I ensure that I will include this file in only one .cpp file only once. Are there still scenarios in which I would require this safe-guard?
No, that's the only purpose of the include guards, but using them should be a no-brainer: doing it requires little time and potentially saves a lot.
You can guarantee that your code only includes it once, but can you guarantee that anyone's code will include it once?
Furthermore, imagine this:
// a.h
typedef struct { int x; int y; } type1;
// b.h
#include "a.h"
typedef struct { type1 old; int z; } type2;
// main.c
#include "a.h"
#include "b.h"
Oh, no! Our main.c only included each once, but b.h includes a.h, so we got a.h twice, despite our best efforts.
Now imagine this hidden behind three or more layers of #includes and it's a minor internal-use-only header that gets included twice and it's a problem because one of the headers #undefed a macro that it defined but the second header #defined it again and broke some code and it takes a couple hours to figure out why there are conflicting definitions of things.
That's its sole raison d'etre. It's still a good idea even if you think you have that covered; it doesn't slow your code down or anything, and it never hurts to have an extra guard.
The purpose of the guard is to prevent the file from being re included in the same .cpp file more than once. It does not protect against including the file in more than one .cpp file.
If you are sure that a header file isn't included in another header file, then the guard is not required. but it's still good form.
even better form is to use
#pragma once
if your compiler supports it.
Ensuring your code is included only once is the sole purpose of a so-called "header guard".
This can be useful as if there's somewhere a circular dependency between your header files, you don't get caught in an endless loop of including files.
The additional scenario I can think of (and we did it) is to create C++ mocks.
You explicitly in your build define the file GUARD value and then you are able to add your own mock realization via -include my_mock.h as the additional compiler option (we used g++).
my_mock.h
#define THAT_FILE_GUARD
class ThatClass
{
void connect()
{
std::cout << "mock connect" << std::endl;
}
}
Using a header guard like this speeds up the compilation process, imagine having three source files using the header (minus the header guard), that in turn would mean the compiler would have to include the header (parsing and lexing the syntax) multiple times over.
With a header guard, the compiler will say 'Ha! I have seen this one before, and no I will not parse/lex the syntax' thereby speeding up the compilation process.
Hope this helps,
Best regards,
Tom.