Is there a standard #include convention for C++? - 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++:

Related

C++ mass-#include

I always need to write #include "headername.h" when including another class. Is it possible to acess other classes without writing it or including more than 1 class with a "#include"?
What the #include directive does is exactly what its name implies, it literally includes the contents of the wanted file into the source. It's done at an early step in the compilation process, before the actual compiler gets the source. The source with all its headers files is called translation unit, and it's on this translation unit that the compiler works on.
As for why you need the header files, remember that C++ needs everything to be declared or defined before it's being used. If the compiler doesn't know there is a class named Foo you can't declare variables of type Foo. If you don't #include the header file there Foo is defined, the compiler simply will not know there is such a class.
If you end up having to include many headers in many source files, you can put the common headers in another header file, whose only purpose is to include other header file. For example, if you in many source file includes <string>, <vector> and <iostream>, then you create a file called headers.h containing
#ifndef HEADERS_H__
#define HEADERS_H__
#include <iostream>
#include <string>
#include <vector>
#endif // HEADERS_H__
Then you can include this file in your source files instead:
#include "headers.h"
You can create your own header file which includes the necessary includes and then include this header file.

Header files and include best practice

I have a quick question regarding header files, include statements, and good coding style. Suppose I have 2 classes with associated source and header files, and then a final source file where main() is located.
Within Foo.hpp I have the following statements:
#include <string>
#include <iostream>
#include <exception>
Now withing Bar.hpp I have the following statements:
#include "Foo.hpp"
#include <string>
And finally withing Myprogram.cpp I have the following statements:
#include "Bar.hpp"
#include <string>
#include <iostream>
#include <exception>
I know the include statements in <> in Myprogram.cpp and Bar.hpp aren't necessary for the program to compile and function, but what is the best practice or right way of doing things? Is there any reason to not explicitly include the necessary header files in each file?
You should include all necessary files in every file that needs them. If MyProgram.cpp needs string, include it, instead of relying on it being included by Bar.hpp. There's no guarantee 2 weeks from now Bar.hpp will still include it, and then you'll be left with compiler errors.
Note the necessary - i.e. make sure you actually need an include, when a forward declaration or even leaving it out completely will do.
Also, note that some system headers might include others - apart from a few exceptions, there's no requirement. So if you need both <iostream> and <string> include both, even if you can compile only with one of them.
The order in which the includes appear (system includes vs user includes) is up to the coding standard you follow - consistency is more important than the choice itself.
Include all you need in every file, but do not include any file that you do not need. Normally, it is the job of the included file to make sure it is not included twice, using precompiler flags, etc...
For example if is needed by Foo.cpp, but not by Foo.h, include it in Foo.cpp not in Foo.h. If required in both, include in both.
Tangentially, as a best practice, never use using directives in a header file. If you need you can use using directives in implementation files (.cpp).

should I include a header that is already included via other headers?

I had only just noticed my programs using the string class were compiling without including the <string> header. It turns out that <iostream> includes <ios_base> which in turn includes <string>.
Is this bad practice and should I explicitly include <string>? Even if it's just a case of clarity?
Is it safe to assume this applies to more than just the <string> header? Perhaps this is implementation specific and or does the standard state the <string> header be included via <ios_base> and <iostream>? Ensuring that any respected and widely used implementation will always include <string> providing the the call to <iostream> exists.
You should explicitly include whatever standard library headers you need.
It is not specified which standard library headers are included by other standard library headers, so such details will differ between compilers.
One case where you can rely on a header being included by another header is if a class in one header derives from a class in another. For example, <iostream> has to include <ios_base> because classes defined in <iostream> are derived from classes defined in <ios_base>.
A good practice is to always include the headers for the classes you'll be using in a given source file, regardless of whether you "know" they're included by already-included files.
If, while refactoring your code, you remove the necessity for one of the higher-level included files (iostream, for example), it could become quite painful to determine why your application no longer compiles.
If you add a proper header (with '#pragma once' or the proper #ifndef) more than once, it only adds a little more time to compiling (just to open, parse and through away the header file contents), but nothing too serious while it makes your files more easy to compile, should the circumstances change (i.e. move them to a different project, make a library out of them, e.t.c.)
If you are really concerned about compile time add the same #ifndef before including the header (though I don't recommend it)
i.e.
// header.h
#ifndef _HEADER_H
#define _HEADER_H
int blahblahblah(int);
#endif
// cppfile.cpp
#ifndef _HEADER_H
#include <header.h>
#endif

#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.

C++ Header Guard issues

I am making a small C++ framework, which contains many .h and .cpp.
I have created a general include which include all my .h file such as:
framework.h
#include "A.h"
#include "B.h"
#include "C.h"
each .h header are protected with include guard such as
#ifndef A_HEADER
#define A_HEADER
...
#endif
The issues is, I would like to be able to include "framework.h" inside all the sub .h such as, but it cause lots of compiler error:
#ifndef A_HEADER
#define A_HEADER
#include "framework.h"
...
#endif
If instead I use the real header file for each sub header, and the framework.h for what ever use my framework it works fine..
I would just like to include the main header inside all my sub .h so I dont need to include all the dependency everytime.
Thanks :)
Basically what your doing is #include "A.h" in framework.h and #include "framework.h" in A.h. This causes cyclic dependency of the header files and you will get errors such as undefined class A. To solve this, use forward declarations in header file and #include only in corresponding cpp file. If that is not possible then I don't see any other option other than including individual header files.
Just protect the main header with include guards too:
#ifndef FRAMEWORK_H
# define FRAMEWORK_H
# include <A.h>
# include <B.h>
# include <C.h>
#endif
That will prevent recursive inclusion.
You should not including the main header file inside the sub-header files. It should be used to make user's life easier, not yours.
Instead do following:
1) Make forward definitions of all you need in the related sub-header files.
2) Include only needed sub-header files inside CPP files.
3) When using your framework inside an application code (for example), then you could include the main framework header file.
i would recommend using #pragma once, and placing that at the top of all of your header files (framework.h, A.h, B.h, and C.h).
Although, if you'd rather, I think you could fix your problem by simply putting an include guard in framework.h as well.
I guess you have a dependency between - say B and C such that B depends on C, but in framework.h C is included after B.
Circular includes are generally a bad idea in C++. While having header guards will prevent the preprocessor from going into infinite loop (or throwing an error because of this), you will get unexpected compiler errors, because at some point a header file will not be included when if you think it is.
You should include A.h, B.h and C.h from framework.h, and in A.h, do not include framework.h, just forward declare the classes you use from it. Or do it the other way around: include framework.h from A.h, B.h and C.h, and forward declare classes in framework.h. And, of course, put every code that would require any more detailed declarations than for example class A to the .cpp files.