Where to #include headers? - c++

I looked up header file examples, but could only find simple ones with nothing to include.
So my question is where do I #include stuff like string and vector? In the .h or the .cpp file? Or maybe in both?

Anywhere you need.
If you need something declared in a header file, include them in the .h file.
Otherwise just in the .cpp file.
Note that including a .h file is just a textual replacement and the contents of the included .h file will be entirely inserted at the beginning of the file where they've been included. at the precise point of the #include line.
It is good practice to include a project-belonging headers before the standard library ones and never include a header if you don't need it.
Last thing you should keep in mind is that when working with large projects including many headers in a .h file shared by many translation units can increase compilation times if the header gets modified. It's usually preferred to just include what you strictly require in the appropriate files (either .cpp or .h). Precompiled headers might also help but it's off-topic to your question.
Finally: don't rely on "this header has been included somewhere else and I'm already including it through a second header" because it could render dependencies-tracking hard and favor circular dependencies when the project grows.

where do I #include stuff like string and vector? In the .h or the .cpp file?
There are multiple issues to consider in this, especially when projects get bigger (i.e. the bigger your project is, the more this affects you).
Personally, I follow these rules:
if code needs a header to compile, then you need to include it (if header declares things with std::string in the API, you will have to include string and the same goes for the C++ file)
do not include headers that are not needed (i.e. not "both" - if you include a header in your .h file, then include your .h file, you should be fine).
organize headers prioritizing for your project's files. this means if you have in a C++ file local project headers, and std and boost headers, you should (probably) include local project headers first, then boost, then std.
This is because the std headers will be the most tested/stable ones, and the most used API (this is a blind supposition on my part). If you were to include std headers first, and then project headers (for example), since the replacement is textual, you could get away with not adding the include in the project header. This would basically mask an error, because you would end up having to include the std headers before the local project header in all other cpp files from now on.

Related

C++ Header and Source file design implementation

I have a few queries regarding the design principle of laying out a C++ header and source files:
I have recently taken over a project in which the previous programmer used to have this, which is particularly annoying because I read somewhere that we shouldn't include a .cpp file in a .hpp file (The preprocessor will just copies and pastes the .cpp file into a .hpp)
Q1. Including a .cpp file in a .hpp file is bad? why?
Due to the problem above, I am facing many "multiple declaration" errors when I load my program in eclipse, even though i added the header guards in all the .hpp files.
Q2. Should i be including the header guards in the .cpp files as well?
I tried the later too but to no avail. Any suggestions on this?
Q3. If 2 or more of my .cpp files need the same header files to be
used what is the best way to include all those header files? Should i
create a new header file say h1.hpp, include all the header files I
need in those 2 or more .cpp files and later include in this header
file in those .cpp files(s)?
Is it an efficient approach ?
Including a .cpp file in a .hpp file is bad? why?
In a typical code setup, yes. It serves no useful purpose and can lead to "duplicate definition" errors.
More importantly, it mixes the separation between the implementation and interface parts. When a file containing implementation is meant to be included, it's often changed to .inl (from "inline") extension.
Should i be including the header guards in the .cpp files as well?
No. Header guards prevent two (or more) other headers in one translation unit from including the same header twice. Since there's only one .cpp file per translation unit, this problem doesn't occur there.
To illustrate, an example inclusion could look like this:
common.hpp
/ \
/ \
A.hpp B.hpp
\ /
\ /
file.cpp
In this case, header guard in common.hpp prevents it from appearing twice in the TU introduced for file.cpp.
If 2 or more of my .cpp files need the same header files to be used what is the best way to include all those header files?
You shouldn't be scared by a long include chain, in general. It's less scary than it looks. That being said, "aggregate" headers can be used if the headers actually form a tree structure (to make including subsets easier, like collections.hpp and collections/vector.hpp + collections/list.hpp) or to include every header from the library.

Including all header files in application

I was recently looking through the source code of a C++ application and saw that each class did not #include its needed components, but instead #include'd a "Precompiled.h" header. In this Precompiled header was an inclusion of almost every header in the application (not all of them, it was clear that the length and order of the list was deliberate). Essentially, this would mean that every class had an inclusion of every other class in the application.
Is this wise? Why or why not?
Usually if you write an application, you should only include header files which are really needed in cpp files. If you got a really big application, you should use forward declaration in the header and include necessary files in the cpp file. With that, changes in code only affects a minimum on cpp files, so the compiler had only to compile what really has changed.
The situation can totally flip, when it comes to libraries or code which does not change very often. The filename "Precompiled.h" is already a hint. The compiler can precompile the headers to a special object file, often called PCH file. With that, the compiler has not to resolve every include on every compile time. On heavy nested includes, this has high impact on compile speed, because instead of many files to load and parse, there is only one preparsed file. To archive that you have to declare one or more headers as a kind of center file for building a precompiled header. How you do that differs between different compilers.
For example Visual studio uses the header file "stdafx.h" as the center of the precompilation of header files. Because of that, only header files should include there which are not altered very often. Also the file had to be included first in every cpp file. That is because the compiler can not detect any more if a include file which is included before may have influence to the precompiled file. To avoid that, includes before the precompiled includes are not allowed.
Back to your question. Including every file in one header file to use it as precompiled header makes no sense at all, as it conteract the meaning of a precompiled header file.
It is a very bad idea.
For a .cpp file only include the minimum number of #include files.
Thereby when one of them changes the make (or moral equilivant) will not require the whole lot to be recompiled.
Saves lots of time during development.
PS Use forward declarations in preference to #include

Organize includes

Is there some preferred way to organize ones include directives?
Is it better to include the files you need in the .cpp file instead of the .h file? Are the translation units affected somehow?
How about if I need it in both the .h file and .cpp file, should I just include it in the .h file? Will it matter?
Is it a good practice to keep the already defined files in a precompiled header (stdafx.h), for instance std and third party libraries? How about my own files, should I include them in a stdafx.h file along the way as I create them?
// myClass.h
#include <string>
// ^-------- should I include it here? --------
class myClass{
myClass();
~myClass();
int calculation()
};
// myClass.cpp
#include "myClass.h"
#include <string>
// ^-------- or maybe here? --------
[..]
int myClass::calculation(){
std::string someString = "Hello World";
return someString.length();
}
// stdafx.h
#include <string.h>
// ^--------- or perhaps here, and then include stdafx.h everywhere? -------
You should have them at the top of the file, all in one place. This is what everyone expects. Also, it is useful to have them grouped, e.g. first all standard headers, then 3rd-party headers (grouped by library), then your own headers. Keep this order consistent throughout the project. It makes it easier to understand dependencies. As #James Kanze points out, it is also useful to put the header that declares the content first. This way you make sure that it works if included first (meaning it does no depend on any includes that it does not include itself).
Keep the scope as small as possible, so that a change in the header affects the least number of translation-units. This means, whenever possible include it in the cpp-file only. As #Pedro d'Aquino commented, you can reduce the number of includes in a header by using forward declarations whenever possible (basically whenever you only use references or pointers to a given type).
Both - explicit is better than implicit.
After some reading, I believe you should only include headers in the PCH if you are confident that they do not change anymore. This goes for all standard headers as well as (probably) third party libraries. For your own libraries, you be the judge.
This article on Header file include patterns should be helpful for you.
Is there some preferred way to organize ones include directives?
Yes, you can find them in the above article.
Is it better to include the files you need in the .cpp file instead of
the .h file? Are the translation units
affected somehow?
Yes, it is better to have them in .cpp. Even, if a defined type is required in definition of another type, you can use forward declaration.
How about if I need it in both the .h file and .cpp file, should I just
include it in the .h file? Will it
matter?
Only in .h file, but it is suggested to forward declare in header files, and include in .cpp files.
Is it a good practice to keep the already defined files in a precompiled
header (stdafx.h), for instance std
and third party libraries? How about
my own files, should I include them in
a stdafx.h file along the way as I
create them?
I personally have not used precompiled headers, but there has been a discussion on them on Stackoverflow earlier:
Precompiled Headers? Do we really need them
Is there some preferred way to organize ones include directives?
No common conventions. Some suggest alphabet-sorting them, I personally dislike it and prefer keeping them logically grouped.
Is it better to include the files you need in the .cpp file instead of the .h file?
In general, yes. It reduces the count of times that the compiler needs to open and read the header file just to see the include guards there. That may reduce overall compilation time.
Sometimes it's also recommended to forward-declare as much classes as possible in the headers and actually include them only in .cpp's, for the same reason. The "Qt people" do so, for example.
Are the translation units affected somehow?
In semantic sense, no.
How about if I need it in both the .h file and .cpp file, should I just include it in the .h file? Will it matter?
Just include it in the header.
Is it a good practice to keep the already defined files in a precompiled header (stdafx.h), for instance std and third party libraries? How about my own files, should I include them in a stdafx.h file along the way as I create them?
Precompiled headers can significantly reduce compilation times. For example: one of my projects that includes boost::spirit::qi compiles in 20 secs with PCH on, and 80 secs — without. In general, if you use some heavily template-stuffed library like boost, you'd want to utilise the advantage of PCH.
As for the question in your code sample: since you don't use std::string in the header, it's better to include it in the .cpp file. It's alright to #include <string> in stdafx.h too — but that will just add a little bit of complexity to your project and you'll hardly notice any compilation speed-up.
(4) I wouldn't recommend to include any additional files into stdafx.h. or similar "include_first.h" files. Direct including into cpp or particular h files allow you to express dependencies of your code explicitly and exclude redundant dependencies. It is especialy helpful when you decide to decompose monolithic code into a few libs or dll's. Personally, I use files like "include_first.h" (stdafx.h) for configuration purpose only (this file contains only macro definitions for current application configuration).
It is possible to provide precompiled headers for your own files by marking another file to stop precompilation instead of stdafx.h (for instance, you can use special empty file named like "stop_pch.h").
Note, precompiled headers may not work properly for some kinds of sofisticated usage of the preprocessor (particulary, for some technics used in BOOST_PP_* )
From the performance point of view:
Changing any of the headers included from stdafx.h will trigger a new precompilation, so it depends on how "frozen" the code is. External libraries are typical candidates for stdafx.h inclusion, but you can certainly include your own libraries as well - it's a tradeoff based on how often you expect to change them.
Also, with the Microsoft compiler you can put this at the top of each header file:
#pragma once
This allows the compiler to fully skip that file after the first occurrence, saving I/O operations. The traditional ifndef/define/endif pattern requires opening and parsing the file every time it's included, which of course takes some time. It can certainly accumulate and get noticeable!
(Make sure to leave the traditional guards in there, for portability.)
It might be important to notice that the order of classes in Translation Unit need to be correct or some c++ features are just disabled and results in a compile-time error.
Edit: Adding examples:
class A { };
class B { A a; }; // order of classes need to be correct

Does it matter whether I put an #include directive in my cpp file or in an included header file?

My c++ program is using a separate header file (Let's call it myHeader.h) and therefore includes it (#include "myHeader.h"). In my program I need to use another header file (Let's call it another.h). Does it make a difference whether I put the #include "another.h" directive in the cpp file or in myHeader.h?
If it's not used in the .h file, then there will be no difference in compilation success/failure.
However, it is recommended to put include for header files you only need in the implementation in the .cpp files for the following reasons:
for encapsulation reasons - no one needs to know what you include solely for the implementation.
Including a file A.h in a header file B.h will also make any file that includes B.h include A.h. That can cause major dependency issues between seemingly unrelated files.
for the above reason, it can also increase build time substantially (every file you include is copied in your compilation unit).
If you need to include a header only in your cpp file then you should include it in your cpp file.
If you include it in your header it will add unneeded dependencies for everyone else who includes your header. This can explode if the unneeded headers you include also include other unneeded headers of their own.
The answer to your question is "No". However, you should try to avoid making unnecessary include statements in your .h files because it will induce longer build times. It is also better for encapsulation reasons as well.
Assuming all your include guards are in place etc then no.
It's best to think of how the user will use the code and try and avoid surprises for them.
In general you should avoid complex trees of include files included form other include files - although precompiled headers on modern compilers help.
BUT you should also make sure that you have all the advanced declarations in place so that the order of includes in a cpp file doesn't matter.
No difference really. Header files and cpp files can both include other files. The included files are effectively copied into the text stream.
There is a difference - every time your h file is included, any files included in that h file are included as well - I haven't kept up-to-date with modern C++ compilers, but this used to really increase compile time.
It also increases the physical dependency of the source - John Lakos' Large Scale C++ Software Design addresses this, and is well worth a read on structuring c++ programs. It's published in 1996, so it's not based around current practice, but the advise on structure is worth knowing.

C++ Header order [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
What order should headers be declared in a header / cpp file? Obviously those that are required by subsequent headers should be earlier and class specific headers should be in cpp scope not header scope, but is there a set order convention / best practice?
In a header file you have to include ALL the headers to make it compilable. And don't forget to use forward declarations instead of some headers.
In a source file:
corresponded header file
necessary project headers
3rd party libraries headers
standard libraries headers
system headers
In that order you will not miss any of your header files that forgot to include libraries by their own.
Good practice: every .h file should have a .cpp that includes that .h first before anything else. This proves that any .h file can be put first.
Even if the header requires no implementation, you make a .cpp that just includes that .h file and nothing else.
This then means that you can answer your question any way you like. It doesn't matter what order you include them in.
For further great tips, try this book: Large-Scale C++ Software Design - it's a shame it's so expensive, but it is practically a survival guide for C++ source code layout.
In header files, I tend to put standard headers first, then my own headers (both lists being ordered alphabetically). In implementation files, I put first the header corresponding (if any), then standards headers and other dependency headers.
Order is of little importance, except if you make a great use of macros and #define ; in that case, you must checked that a macro you defined doesn't replace a previously included one (except if that's what you want, of course).
Concerning this statement
those that are required by subsequent headers should be earlier
A header shouldn't rely on other headers being included before it! If it requires headers, it just includes them. Header guards will prevent multiple inclusion:
#ifndef FOO_HEADER_H
#define FOO_HEADER_H
...
#endif
EDIT
Since I wrote this answer, I changed my way of ordering the include directives in my code. Now, I try to always put headers in increasing order of standardization, so the headers of my project come first, followed by 3rd party libraries headers, followed by standard headers.
For instance, if one of my file uses a library I wrote, Qt, Boost and the standard library, I will order the includes as follow:
//foo.cpp
#include "foo.hpp"
#include <my_library.hpp>
// other headers related to my_library
#include <QtCore/qalgorithms.h>
// other Qt headers
#include <boost/format.hpp> // Boost is arguably more standard than Qt
// other boost headers
#include <algorithms>
// other standard algorithms
The reason why I do that is to detect missing dependencies in my own headers: let's assume for instance that my_library.hpp uses std::copy, but doesn't include <algorithm>. If I include it after <algorithm> in foo.cpp, this missing dependency will go unnoticed. On the contrary, with the order I just presented, the compiler will complain that std::copy has not been declared, allowing me to correct my_library.hpp.
In each "library" group, I try to keep the include directives ordered alphabetically, to find them more easily.
On a sidenote, a good practice is also to limit at a maximum the dependency between header files. Files should include as little headers as possible, especially headers file. Indeed, the more headers you include, the more code needs to be recompiled when something changes. A good way to limit these dependencies is to use forward declaration, which is very often sufficient in header files (see When can I use a forward declaration?).
Google C++ Style Guide, Names and Order of Includes :
In dir/foo.cc, whose main purpose is to implement or test the stuff in dir2/foo2.h, order your includes as follows:
dir2/foo2.h (preferred location — see details below).
C system files.
C++ system files.
Other libraries' .h files.
Your project's .h files.
I used to order them in alphabetical order (easier to find)
The "how" is not obvious, but the "what" is.
Your goal is to make sure that the order in which you include header files never matters (and i mean "NEVER !").
A good help is to test whether header files compile when building cpp files (one for each header file) that only include one of them.
For .cpp files, you should include the header of the class or whatever you are implementing first, so you catch the case where this header is missing some includes. After that, most coding guidelines tend to include system headers first, project headers second, for example the Google C++ Style Guide.
It's a dependency thing and it depends largely on what you put in our headers. A fact is that you can be really notorious about this and minimize to keep your includes strict but you'll eventually run into a scenario where you'll wanna use inclusion guards.
#ifndef MY_HEADER_H
#define MY_HEADER_H
//...
#endif
The problem isn't that apparent in the beginning, but as the complexity of your software grows so does your dependencies. You can do well, and be smart about it but larger C++ projects are generally riddled with includes. You can try, but you can only do so much. So be diligent and think about your includes, YES! But you'll most certainly have cyclic dependencies at some point and that is why you need inclusion guards.
If a header needs other headers then it just includes them in that header.
Try to structure your code so you pass pointers or references and forward declare where you can.
In the implementation then the header that defines it should be listed first (except in Visual Studio if you are using pch then stdafx would go first).
I generally list them as I need.
I've found the following convention the most useful:
module.cpp:
// this is the header used to trigger inclusion of precompiled headers
#include <precompiled.h>
// this ensures that anything that includes "module.h" works
#include "module.h"
// other headers, usually system headers, the project
The important thing is to put the module's header as the first non-precompiled header. This ensures "module.h" has no unexpected dependencies.
If you're working on a large project with slow disk access times, I've seen this style used to decrease build times:
module.cpp:
// this is the header used to trigger inclusion of precompiled headers
#include <precompiled.h>
// this ensures that anything that includes "module.h" works
#include "module.h"
// other headers, usually system headers, the project
#if !defined _OTHER_MODULE_GUARD_
#include "other_module.h"
#endif
#if !defined _ANOTHER_MODULE_GUARD_
#include "another_module.h"
#endif
It's a bit verbose but does save on disk seeking since the header won't be searched for / opened if it's already been included. Without the guard check, the compiler will seek for and open the header file, parse the whole file to end up #ifdefing the whole file out.