Header guards for bigger projects - c++

I understand what a header guard is but I never saw how it is used in bigger projects. I am currently writing an OpenGL abstraction layer and I mostly need to include the same files.
So my first naive approach was to do something like this:
#ifndef GUARD_H
#define GUARD_H
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <GL/glfw3.h>
#include <glload/gl_core.h>
#include <glload/gll.h>
#endif // GUARD_H
So I can just do #include "guard.h". But I realized that this is not a really good solution because what if I want to add a simple include?
Yes I probably could write all my includes in this file but I am also not sure if this is a good idea either.
How would you recommend me to structure my header guards? Can you recommend me any resources?
Update 1: small example
test.h
#ifndef TEST_H
#define TEST_H
#include <glm/glm.hpp>
class test{
};
#endif
test1.h
#ifndef TEST1_H
#define TEST1_H
#include <glm/glm.hpp>
class test1{
};
#endif
now I included glm in my test class. but what if I want to do something like this.
#include "test.h"
#include "test1.h"
int main(){
//...
}
Don't I include #include <glm/glm.hpp> 2 times in main?

It's not a good idea to put all your includes in one files, except if you always include all those file.
You should only include the strict minimum of required headers in your own headers and include the rest directly in your .cpp source files.
Each of your headers should have a unique header guard without conflict with any other library, so take a very good care of the naming scheme.
You may also consider using the non-standard #pragma once directive, if you're not writing portable code.
You could take a look at this paper about the best practice for designing header files
To answer your edit :
No you don't include <glm/glm.hpp> twice, because it has itself a header guard. But you should include it only if you actually need glm.hpp inside your header, otherwise you should include it later. Note that you can often avoid the include by forward-declaring what you need, that could speed-up the compilation and avoid circular dependency, but that's another issue.

Simple. Header guards in every single header.
The way you've done it is unsafe : What if one day someone (not necessarily you, though even this is unsure) includes directly one of the headers you listed (though these are mostly external libs it seems, but it could evolve to include one of yours...), and this header doesn't have include guards ? Might as well exclude this possible issue ASAP !
To structure your headers, you should prefer to include what is strictly needed rather than everything in one global header.
Edit answer : No you won't include it twice. After the first include, every extra occurrence of the header guarded file will simply be ignored.

Related

Comprehension issue: Precompiled headers & include usage

I got a comprehension issue about precompiled headers, and the usage of the #include directive.
So I got my "stdafx.h" here and include there for example vector, iostream and string. The associated "stdafx.cpp" only includes the "stdafx.h", that's clear.
So if I design my own header file that uses for example "code" that's in vector or iostream, I have to include the header file because the compiler doesn't know the declarations at that time. So why are some posts here (include stdafx.h in header or source file?) saying, it's not good to include the "stdafx.h" in other header files even if this file includes the needed declarations of e.g. vectors? So basically it wouldn't matter to include directly a vector or the precompiled header file, both do the same thing.
I know of course, that I don't have to include a header file in another header file if the associated source file includes the needed header file, because the declarations are known at that time. Well, that only works if the header file is included somewhere.
So my question is: Should I avoid including the precompiled header file in any source file and why? And I am a bit confused, because I'm reading contradictory expressions on the web that I shouldn't include anything in header files anyway, or is it O.K. to include in header files?
So what's right now?
This will be a bit of a blanket statement with intent. The typical setup for PCH in a Visual Studio project follows this general design, and is worth reviewing. That said:
Design your header files as if there is no PCH master-header.
Never build include-order dependencies in your headers that you expect the including source files will fulfill prior to your headers.
The PCH master-header notwithstanding (I'll get to that in a moment), always include your custom headers before standard headers in your source files. This makes your custom header is more likely to be properly defined and not reliant on the including source file's previous inclusion of some standard header file.
Always set up appropriate include guards or pragmas to avoid multiple inclusion. They're critical for this to work correctly.
The PCH master-header is not to be included in your header files. When designing your headers, do so with the intent that everything needed (and only that which is needed) by the header to compile is included. If an including source file needs additional includes for its implementation, it can pull them in as needed after your header.
The following is an example of how I would setup a project that uses multiple standard headers in both the .h and .cpp files.
myobject.h
#ifndef MYAPP_MYOBJECT_H
#define MYAPP_MYOBJECT_H
// we're using std::map and std::string here, so..
#include <map>
#include <string>
class MyObject
{
// some code
private:
std::map<std::string, unsigned int> mymap;
};
#endif
Note the above header should compile in whatever .cpp it is included, with or without PCH being used. On to the source file...
myobject.cpp
// apart from myobject.h, we also need some other standard stuff...
#include "myobject.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
// code, etc...
Note myobject.h does not expect you to include something it relies on. It isn't using <iostream> or <algorithm>, etc. in the header; we're using it here.
That is a typical setup with no PCH. Now we add the PCH master
Adding the PCH Master Header
So how do we set up the PCH master-header to turbo-charge this thing? For the sake of this answer, I'm only dealing with pulling in standard headers and 3rd-party library headers that will not undergo change with the project development. You're not going to be editing <map> or <iostream> (and if you are, get your head examined). Anyway...
See this answer for how a PCH is typically configured in Visual Studio. It shows how one file (usually stdafx.cpp) is responsible for generating the PCH, the rest of your source files then use said-PCH by including stdafx.h.
Decide what goes in the PCH. As a general rule, that is how your PCH should be configured. Put non-volatile stuff in there, and leave the rest for the regular source includes. We're using a number of system headers, and those are going to be our choices for our PCH master.
Ensure each source file participating in the PCH turbo-mode is including the PCH master-header first, as described in the linked answer from (1).
So, first, the PCH master header:
stdafx.h
#ifndef MYAPP_STDAFX_H
#define MYAPP_STDAFX_H
// MS has other stuff here. keep what is needed
#include <algorithm>
#include <numeric>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#endif
Finally, the source files configured to use this then do this. The minimal change needed is:
UPDATED: myobject.cpp
#include "stdafx.h" // <=== only addition
#include "myobject.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
// code, etc...
Note I said minimal. In reality, none of those standard headers need appear in the .cpp anymore, as the PCH master is pulling them in. In other words, you can do this:
UPDATED: myobject.cpp
#include "stdafx.h"
#include "myobject.h"
// code, etc...
Whether you choose to or not is up to you. I prefer to keep them. Yes, it can lengthen the preprocessor phase for the source file as it pulls in the headers, runs into the include-guards, and throws everything away until the final #endif. If your platform supports #pragma once (and VS does) that becomes a near no-op.
But make no mistake: The most important part of all of this is the header myobject.h was not changed at all, and does not include, or know about, the PCH master header. It shouldn't have to, and should not be built so it has to.
Precompiled headers are a method to shorten the build time. The idea is that the compiler could "precompile" declarations and definitions in the header and not have to parse them again.
With the speed of todays computers, the precompilation is only significant for huge projects. These are projects with a minimum of over 50k lines of code. The definition of "signification" is usually tens of minutes to build.
There are many issues surrounding Microsoft's stdafx.h. In my experience, the effort and time spent with discovering and resolving the issues, makes this feature more of a hassle for smaller project sizes. I have my build set up so most of the time, I am compiling only a few files; the files that don't change are not compiled. Thus, I don't see any huge impact or benefit to the precompiled header.
When using the precompiled header feature, every .cpp file must begin by including the stdafx.h header. If it does not, a compiler error results. So there is no point in putting the include in some header file. That header file cannot be included unless the stdafx.h has already been included first.

Single header which includes other headers

Recently, I encountered such approach of managing headers. Could not find much info on its problems on internet, so decided to ask here.
Imagine you have a program where you have main.c, and also other sources and headers like: person.c, person.h, settings.c, settings.h, maindialog.c, maindialog.h, othersource.c, othersource.h
sometimes settings.c might need person.c and main maindialog.c.
Sometimes some other source might need to include other source files.
Typically one would do inside settings.c:
//settings.c
#include "person.h"
#include "maindialog.h"
But, I encountered approach where one has global.h and inside it:
//global.h
//all headers we need
#include "person.h"
#include "maindialog.h"
#include "settings.h"
#include "otherdialog.h"
Now, from each other source file you only have to include "global.h"
and you are done, you get functionality from respective source files.
Does this approach with one global.h header has some real problems?
This is to please both pedantic purists and lazy minimalists. If all sub-headers are done the correct way there is no functional harm including them via global.h, only possible compile time increase.
Subheader would be somewhat like
#ifndef unique_token
#define unique_token
#pragma once
// the useful payload
#endif
If there are common headers that all the source files need, (like config.h) you can do so. (but use it like precompiled headers...)
But by including unnecessary headers, you actually increasing the compilation time. so if you have a really big project and for every source file you including all the headers, compilation time can be very long...
I suggest not include headers unless you must.
Even if you use type, but only for pointer or reference (especially in headers), prefer to use fwd declaration instead of include.

Management of lot of #include statements and header files

In my current project. A lot of my .cpp and .h files have plenty of includes in them such as 6 or 7 of headers declared in the following manner.
#ifndef A_Header
#include "a.h"
#endif
#ifndef B_Header
#include "b.h"
#endif
I wanted to know would it make sense if I wrapped all of these headers (used in the project) in a single header and then declare that header in each source file as such
#ifndef Wrapper_Header
#include "wrapper.h" /*This would contain a collection of all headers*/
#endif
Any suggestions and drawbacks of this plan that I am not anticipating?
That's totally bizarre.
Every header should contain a header guard:
#ifndef THIS_HEADER
#define THIS_HEADER
/* contents of the header */
#endif
This goes inside the header, not in the including .cpp file. The compiler detects the header guard and avoids re-reading all the text when it's included again. This can save seconds of compilation time.
If your headers have that, then the guards in the .cpp file are extraneous and you should remove them. 6 or 7 headers isn't a lot, but that silly boilerplate does sure add up.
Never wrap your headers, always be explicit, make it clear what is included, and do not include what you do not need.
Potatoswatter is correct
But I like to add use "forward declaration".
I am sure you can google it.

#include in .h or .c / .cpp?

When coding in either C or C++, where should I have the #include's?
callback.h:
#ifndef _CALLBACK_H_
#define _CALLBACK_H_
#include <sndfile.h>
#include "main.h"
void on_button_apply_clicked(GtkButton* button, struct user_data_s* data);
void on_button_cancel_clicked(GtkButton* button, struct user_data_s* data);
#endif
callback.c:
#include <stdlib.h>
#include <math.h>
#include "config.h"
#include "callback.h"
#include "play.h"
void on_button_apply_clicked(GtkButton* button, struct user_data_s* data) {
gint page;
page = gtk_notebook_get_current_page(GTK_NOTEBOOK(data->notebook));
...
Should all includes be in either the .h or .c / .cpp, or both like I have done here?
Put as much as you can in the .c and as little as possible in the .h. The includes in the .c are only included when that one file is compiled, but the includes for the .h have to be included by every file that uses it.
The only time you should include a header within another .h file is if you need to access a type definition in that header; for example:
#ifndef MY_HEADER_H
#define MY_HEADER_H
#include <stdio.h>
void doStuffWith(FILE *f); // need the definition of FILE from stdio.h
#endif
If header A depends on header B such as the example above, then header A should include header B directly. Do NOT try to order your includes in the .c file to satisfy dependencies (that is, including header B before header A); that is a big ol' pile of heartburn waiting to happen. I mean it. I've been in that movie several times, and it always ended with Tokyo in flames.
Yes, this can result in files being included multiple times, but if they have proper include guards set up to protect against multiple declaration/definition errors, then a few extra seconds of build time isn't worth worrying about. Trying to manage dependencies manually is a pain in the ass.
Of course, you shouldn't be including files where you don't need to.
Put as many includes in your cpp as possible and only the ones that are needed by the hpp file in the hpp. I believe this will help to speed up compilation, as hpp files will be cross-referenced less.
Also consider using forward declarations in your hpp file to further reduce the include dependency chain.
If I #include <callback.h>, I don't want to have to #include lots of other header files to get my code to compile. In callback.h you should include everything needed to compile against it. But nothing more.
Consider whether using forward declarations in your header file (such as class GtkButton;) will suffice, allowing you to reduce the number of #include directives in the header (and, in turn, my compilation time and complexity).
I propose to simply include an All.h in the project that includes all the headers needed, and every other .h file calls All.h and every .c/.cpp file only includes its own header.

Is there a standard #include convention for C++?

This is a rather basic question, but it's one that's bugged me for awhile.
My project has a bunch of .cpp (Implementation) and .hpp (Definition) files.
I find that as I add additional classes and more class inter-dependencies, I have to #include other header files. After a week or two, I end up with #include directives in lots of places. Later, I'll try removing some of the #includes and discover that everything still works because some OTHER included class is also #including what I just removed.
Is there a simple, easy rule for putting in #includes that will stop this ugly mess from happening in the first place? What is the best practice?
For example, I've worked on projects where the Implementation .cpp file ONLY includes the corresponding Definition .hpp file, and nothing else. If there are any other .hpp files that need to be used by the Implementation .cpp, they are all referenced by the Definition .hpp file.
Some best practices:
Every .cpp or .C file includes all headers it needs and does not rely on headers including other related headers
Every .hpp or .h file includes all its dependencies and does not rely on the included headers including other related headers
Every header is wrapped with:
#ifndef HEADER_XXX_INCLUDED
#define HEADER_XXX_INCLUDED
...
#endif /* HEADER_XXX_INCLUDED */
Headers do not include each others in cycles
Often: there is a single "project-wide header file" like "config.h" or ".h" which is always included first by any .cpp or .C file. Typically this has platform related configuration data, project-wide constants and macros etc.
These are not necessarily "best practice", but rules which I usually follow also:
Project-specific headers are included as #include "..." and before the system-wide headers, which are included as #include <...>
Project-specific headers are included in alphabetical order as a way to ensure that there is no accidental, hidden requirement on which order they are included. As every header should include its dependents and the headers should be protected against multiple inclusion, you should be able to include them in any order you wish.
Check out John Lakos's Large-Scale C++ Software Design. Here's what I follow (written as an example):
Interface
// foo.h
// 1) standard include guards. DO NOT prefix with underscores.
#ifndef PROJECT_FOO_H
#define PROJECT_FOO_H
// 2) include all dependencies necessary for compilation
#include <vector>
// 3) prefer forward declaration to #include
class Bar;
class Baz;
#include <iosfwd> // this STL way to forward-declare istream, ostream
class Foo { ... };
#endif
Implementation
// foo.cxx
// 1) precompiled header, if your build environment supports it
#include "stdafx.h"
// 2) always include your own header file first
#include "foo.h"
// 3) include other project-local dependencies
#include "bar.h"
#include "baz.h"
// 4) include third-party dependencies
#include <mysql.h>
#include <dlfcn.h>
#include <boost/lexical_cast.hpp>
#include <iostream>
Precompiled Header
// stdafx.h
// 1) make this easy to disable, for testing
#ifdef USE_PCH
// 2) include all third-party dendencies. Do not reference any project-local headers.
#include <mysql.h>
#include <dlfcn.h>
#include <boost/lexical_cast.hpp>
#include <iosfwd>
#include <iostream>
#include <vector>
#endif
I always use the principle of least coupling. I only include a file if the current file actually needs it; if I can get away with a forward declaration instead of a full definition, I'll use that instead. My .cpp files always have a pile of #includes at the top.
Bar.h:
class Foo;
class Bar
{
Foo * m_foo;
};
Bar.cpp:
#include "Foo.h"
#include "Bar.h"
Use only the minimum amount of includes needed. Useless including slows down compiling.
Also, you don't have to include a header if you just need to pointer to a class. In this case you can just use a forward declaration like:
class BogoFactory;
edit: Just to make it clear. When I said minimum amount, I didn't mean building include chains like:
a.h
#include "b.h"
b.h
#include "c.h"
If a.h needs c.h, it needs to be included in a.h of course to prevent maintenance problems.
There are several problems with the #include model used in C/C++, the main one being that it doesn't express the actual dependency graph. Instead it just concatenates a bunch of definitions in a certain order, often resulting in definitions coming in a different order in each source file.
In general, the include file hierarchy of your software is something you need to know in the same way as you know your datastructures; you have to know which files are included from where. Read your source code, know which files are high up in the hierarchy so you can avoid accidentally adding an include so that it will be included "from everywhere". Think hard when you add a new include: do I really need to include this here? What other files will be drawn in when I do this?
Two conventions (apart from those already mentioned) which can help out:
One class == one source file + one header file, consistently named. Class A goes in A.cpp and A.h. Code templates and snippets are good here to reduce the amount of typing needed to declare each class in a separate file.
Use the Impl-pattern to avoid exposing internal members in a header file. The impl pattern means putting all internal members in a struct defined in the .cpp file, and just have a private pointer with a forward declaration in the class. This means that the header file will only need to include those headerfiles needed for its public interface, and any definitions needed for its internal members will be kept out of the headerfile.
Building on what antti.huima said:
Let's say you have classes A, B, and C. A depends on (includes) B, and both A and B depend on C. One day you discover you no longer need to include C in A, because B does it for you, and so you remove that #include statement.
Now what happens if at some point in the future you update B to no longer use C? All of a sudden A is broken for no good reason.
In A.cpp, always include A.h first, to ensure that A.h has no additional dependencies.
Include all local (same module) files before all project files before all system files, again to ensure that nothing depends on pre-included system files.
Use forward declarations as much as possible.
Use #indef/#define/#endif pattern
If a header is included in A.h, you don't need to include it in A.cpp. Any other headers A.cpp needs must be explicitly included, even if they happen to be provided by other .h files.
Organizing code files in C and C++: