Organize includes - c++

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

Related

Where to #include headers?

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.

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

Does putting a whole class definition in a ".h" make the executable larger?

We define a C++ class in a .h and define its methods in a .cpp, but it makes the code look less organized.
I want to put all method's definition in the class definition which is in a .h file, but I'm worrying that the compiler generate duplicated code for the same methods/functions when one class header file is included by different files.
Does the linker find out and merge the duplicated code pieces to reduce the file size?
If not, is it better to use .hpp instead? I heard that a .hpp is for this.
And it does make minor difference when I just change a .h file for a .hpp (I don't know why), compiled with G++.
Yes. It may create larger executable and that is because the member functions which are defined in the class itself, are inline by default, whether you mention the keyword inline in the defintion or not. Usually, inline function causes larger executable because the compiler will define it multiple times wherever it is called from.
.h vs .hpp is the 90% equivalence of
#include <cmath> vs #include <math.h>
Some people prefer to use .hpp when they are doing exclusive C++ programming. You will see .hpp in libraries like Boost.
However, the other 10% is really important. For example, taking from Boost library doc, they explain the reason of using .hpp over .h:
Most Boost libraries are header-only: they consist entirely of header
files containing templates and inline functions, and require no
separately-compiled library binaries or special treatment when
linking.
If you fall in that case, you should use .hpp, but this can cost longer compilation time. Otherwise, you might want to keep .h style. That's just my personal taste. It isn't C-oriented at all, in my honest opinion.
Further reading:
Splitting templated C++ classes into .hpp/.cpp files--is it possible?
Condensing Declaration and Implementation into an HPP file
C++ templates declare in .h, define in .hpp
You have nothing to worry about. It makes absolutely no difference how it's broken up, it's what your files describe that makes it bigger, not how that description is spread out.
.h or .hpp makes no difference as well.
To answer your question about a larger executable, yes it will make your executable larger. When a you #include a header file in a source or header file, the preprocessor replaces the #include with the contents of the header file. This is why it is necessary to protect your header files with the following header protection:
#ifndef HDR_H
#define HDR_H
...
#endif
However, you will get linker errors if you include the header file (that has function definitions) in multiple files that are part of the same executable. It would wise for you to split class and function definitions and declarations into .cpp and .hpp files, respectively. This will greatly reduce the amount of linker headaches.
Also, .h = .hpp. Doesn't matter which one you choose. Personal preference...
There's all you need here: Header files, pros and cons of putting all you code in them. Hope it helps!
Using header files results in quicker compile time and smaller executable. It also looks considerably cleaner because you can get a quick overview of your class by looking at its .h declaration.

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.