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.
Related
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.
We have been asked a question in a practice paper 'What is the role of the header file in compilation? What are header guards used for in this context?'
A header file will have any declarations for classes which may be included in .cpp implementations. I understand that by including a header file in an implementation or other header file, it is possible for that code to know all the possible members of the class without knowing its implementation.
Having done a little reading through StackOverflow, some have suggested that header files can possibly slow down compilation (Coding C++ (mostly) in header files vs .cpp files) and that while a change to a header file will require a full rebuild of all implementations, while a change to an implementation does not require a full rebuild of the header file and all its implementations.
Would these be accurate? Is there any reason that a header file is necessary of beneficial in compilation and what role does it play?
Many thanks!
yes, although I would avoid using the term implementations for code files - people may think you are talking about the implementation of the class(es) in the headers, which could lead to confusion.
Also, changing a header file will not result in you needing to rebuild all the code files - only those which include (directly or otherwise) said header file.
Oh, and header guards are used to avoid the same file being included twice in a given compilation unit (resulting in redefinitions of things).
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
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.
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.