I have an age-old question.
I'm developing an infrastructure code in C++ which has a lot of headers to be included in each header file.
I ideally would like to have everything included in a header file and then just to include that header file. That of course creates infinite-loop problem where a header is included in a header that includes the same header.
Doing #ifndef or #pragma once is also not going to help.
Is there any other clever way to achieve this?
Thanks
That of course creates infinite-loop problem where a header is included in a header that includes the same header.
Simply exclude the "superheader" from the set of headers that the "superheader" includes. That way you don't get the problem.
That said, doing this is likely going to cause translation units including the "superheader" to include headers unnecessarily which may adversely affect compilation times. As such, I don't recommend this approach.
A header library is a library with all the code in the header.
If I have two cpp files that need code from the header lib, and if they both import the header, and both get compiled, the header file is getting compiled twice, I think. Would linking now throw and error because the header lib functions are being defined twice? If not an error, is this still bad practice?
What is the correct way to handle a header lib?
Just #include everywhere you want. If the library is not horribly broken, it will work fine. The library itself is responsible for having mechanisms that make it usable, in case of a header only library that means making it usable by including the header(s).
Nothing would make this bad practice, simply using by including is the purpose of a header only library.
Header files will use include guards (Include Guard wiki) that keep library functions from being defined twice. Basically, a header file will use a conditional statement that is evaluated during compilation that checks for an existing library definition. If it is defined already it ignores anymore additional definitions. These guards look like this:
/* library_name.h */
#ifndef SOME_IDENTIFIER
#define SOME_IDENTIFIER
[function prototypes]
#endif
A Daniel's Computer Blog article (Here) provides a very digestable explanation of what's going on behind the scenes and flushes out more nuances that I didn't address.
Baum mit Augen is right. If the lib uses include guards there will be no problem using #include<library_name> anywhere you want as many times as you want.
Ideally you will use #include<library_name> once at the top of any file that uses a function/class/constant from the library.
I've searched all over for some clarification on what
#pragma once
actually does and can't find definitive answers for some questions I still have.
Does
#pragma once
insure that the header file it is included in is only called once AS WELL AS that the headers which are included in said header file are not yet included? Also, if it is only called once, does that mean a .cpp file that needs a particular header will not be able to access it? If a header file is marked with
#pragma once
and included in a .cpp, can that header file be used again elsewhere?
These are the sorts of clarifications I am not finding. Sorry if there is documentation that clarifies this somewhere, but I really couldn't find any thing specific enough.
#pragma once only guards a single file in a single translation unit, not counting its sub-hierarchy of inclusion. (However, if the file's second inclusion is prevented, it doesn't have an opportunity to doubly-include anything else.)
You can still include it again from another .cpp.
The file is usually identified by its inode number.
Note that #pragma once is strictly nonstandard, and most still prefer traditional #ifndef header guards.
#pragma once causes the current source file to be included only once in a single compilation.
It's essentially similar to #include guards.
Does #pragma once insure that the header file it is included in is only called once AS WELL AS that the headers which are included in said header file are not yet included?
The pragma doesn't affect other headers. if the header with the pragma 'a.h' includes 'b.h', 'b.h' can be included again via a third header or directly.
Also, if it is only called once, does that mean a .cpp file that needs a particular header will not be able to access it?
You can include the header from anywhere you want, as many times as you see fit.
If a header file is marked with #pragma once and included in a .cpp, can that header file be used again elsewhere?
Yes, this is the normal practice with headers.
Where's the catch?
If you really need to include the headers more than once and every include performs a different operation than don't use pragma once or a sentry macro. These cases are not common.
A benefit to pragma once is that it saves you from bugs like having 2 header files that by chance have the same sentry macro. this can happen when 2 header files have the same file name and same coding style for macro names.
I don't understand why header guards are not used in pre-compiled headers... Any ideas?
Because "stdafx.h" has to be the first include in .cpp files, not anywhere else.
If all you do is include other headers, there's no need. If those files can not be included multiple times, they will have their own header guards. stdafx.h itself doesn't care how many times it is included unless you're using it wrong.
Usually, stdafx.h will be included only once per cpp file, as the first statement, and normally, no other files will include it. So, chances of recursively including stdafx.h are minimal, thus the "unnecessariness" of the include guard.
I would still advise to use one, just in case, or potentially use #pragma once at the top of the file.
I do not know the code of the precompiled header, but I guess it contains a "#pragma once", which has the same effect but only works in VS (at least it's not standard). I remember wizard created MFC files using these.
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.