I'm collaborating with a friend using MSVC and I'm using clang. One thing I've noticed is that clang seems to be automatically including some standard headers, while MSVC is not. For example, I just used the functions assert() and round() from assert.h and math.h respectively.
The code complied fine for me without explicitly including the headers -- is there a switch to turn this behavior off? It's driving me up a wall. I want there to be an error unless I explicitly include the header.
The Standard allows standard header files to include each other, or forward declare items normally found in other files... most likely what is happening is that these definitions are being provided (directly or indirectly) by one of the headers you are including.
This behavior is Standard-conformant, so unfortunately writing portable code is going to require testing using multiple compilers.
A C++ header may include other C++ headers. A C++ header shall provide the declarations and definitions that appear in its synopsis. A C++ header shown in its synopsis as including other C++ headers shall provide the declarations and definitions that appear in the synopses of those other headers.
Certain types and macros are defined in more than one header. Every such entity shall be defined such that any header that defines it may be included after any other header that also defines it (3.2).
The C standard headers (D.5) shall include only their corresponding C++ standard header, as described in 17.6.1.2.
In addition to headers included by other headers, there's also the fact that the C++ headers may or may not introduce global names, while the C headers may or may not introduce names inside namespace std. I've seen a lot of people recommending "This is C++, you should be using <cxyz> instead of xyz.h". This advice is misleading; the two headers do not provide the same definitions, so inclusions of the C++ header cannot simply replace inclusion of the C header. Whether all the code should be rewritten to use the C++ qualified names instead is debatable... but is a prerequisite for changing the includes.
One thing that may help you is to list the headers actually used using gcc -M. Then you can decide whether any of the indirectly included headers should be listed in your code.
Standard headers can include each other. The headers you want to not include might be included by another header you use.
In this case you may want to manually #define the header guards of the headers you don't want before including anything, but that's a little dirty.
Related
What order should include files be specified, i.e. what are the reasons for including one header before another?
For example, do the system files, STL, and Boost go before or after the local include files?
I don't think there's a recommended order, as long as it compiles! What's annoying is when some headers require other headers to be included first... That's a problem with the headers themselves, not with the order of includes.
My personal preference is to go from local to global, each subsection in alphabetical order, i.e.:
h file corresponding to this cpp file (if applicable)
headers from the same component,
headers from other components,
system headers.
My rationale for 1. is that it should prove that each header (for which there is a cpp) can be #included without prerequisites (terminus technicus: header is "self-contained"). And the rest just seems to flow logically from there.
The big thing to keep in mind is that your headers should not be dependent upon other headers being included first. One way to insure this is to include your headers before any other headers.
"Thinking in C++" in particular mentions this, referencing Lakos' "Large Scale C++ Software Design":
Latent usage errors can be avoided by ensuring that the .h file of a component parses by itself – without externally-provided declarations or definitions... Including the .h file as the very first line of the .c file ensures that no critical piece of information intrinsic to the physical interface of the component is missing from the .h file (or, if there is, that you will find out about it as soon as you try to compile the .c file).
That is to say, include in the following order:
The prototype/interface header for this implementation (ie, the .h/.hh file that corresponds to this .cpp/.cc file).
Other headers from the same project, as needed.
Headers from other non-standard, non-system libraries (for example, Qt, Eigen, etc).
Headers from other "almost-standard" libraries (for example, Boost)
Standard C++ headers (for example, iostream, functional, etc.)
Standard C headers (for example, cstdint, dirent.h, etc.)
If any of the headers have an issue with being included in this order, either fix them (if yours) or don't use them. Boycott libraries that don't write clean headers.
Google's C++ style guide argues almost the reverse, with really no justification at all; I personally tend to favor the Lakos approach.
I follow two simple rules that avoid the vast majority of problems:
All headers (and indeed any source files) should include what they need. They should not rely on their users including things.
As an adjunct, all headers should have include guards so that they don't get included multiple times by over-ambitious application of rule 1 above.
I also follow the guidelines of:
Include system headers first (stdio.h, etc) with a dividing line.
Group them logically.
In other words:
#include <stdio.h>
#include <string.h>
#include "btree.h"
#include "collect_hash.h"
#include "collect_arraylist.h"
#include "globals.h"
Although, being guidelines, that's a subjective thing. The rules on the other hand, I enforce rigidly, even to the point of providing 'wrapper' header files with include guards and grouped includes if some obnoxious third-party developer doesn't subscribe to my vision :-)
To add my own brick to the wall.
Each header needs to be self-sufficient, which can only be tested if it's included first at least once
One should not mistakenly modify the meaning of a third-party header by introducing symbols (macro, types, etc.)
So I usually go like this:
// myproject/src/example.cpp
#include "myproject/example.h"
#include <algorithm>
#include <set>
#include <vector>
#include <3rdparty/foo.h>
#include <3rdparty/bar.h>
#include "myproject/another.h"
#include "myproject/specific/bla.h"
#include "detail/impl.h"
Each group separated by a blank line from the next one:
Header corresponding to this cpp file first (sanity check)
System headers
Third-party headers, organized by dependency order
Project headers
Project private headers
Also note that, apart from system headers, each file is in a folder with the name of its namespace, just because it's easier to track them down this way.
I recommend:
The header for the .cc module you're building. (Helps ensure each header in your project doesn't have implicit dependencies on other headers in your project.)
C system files.
C++ system files.
Platform / OS / other header files (e.g. win32, gtk, openGL).
Other header files from your project.
And of course, alphabetical order within each section, where possible.
Always use forward declarations to avoid unnecessary #includes in your header files.
I'm pretty sure this isn't a recommended practice anywhere in the sane world, but I like to line system includes up by filename length, sorted lexically within the same length. Like so:
#include <set>
#include <vector>
#include <algorithm>
#include <functional>
I think it's a good idea to include your own headers before other peoples, to avoid the shame of include-order dependency.
This is not subjective. Make sure your headers don't rely on being #included in specific order. You can be sure it doesn't matter what order you include STL or Boost headers.
First include the header corresponding to the .cpp... in other words, source1.cpp should include source1.h before including anything else. The only exception I can think of is when using MSVC with pre-compiled headers in which case, you are forced to include stdafx.h before anything else.
Reasoning: Including the source1.h before any other files ensures that it can stand alone without it's dependencies. If source1.h takes on a dependency on a later date, the compiler will immediately alert you to add the required forward declarations to source1.h. This in turn ensures that headers can be included in any order by their dependants.
Example:
source1.h
class Class1 {
Class2 c2; // a dependency which has not been forward declared
};
source1.cpp
#include "source1.h" // now compiler will alert you saying that Class2 is undefined
// so you can forward declare Class2 within source1.h
...
MSVC users: I strongly recommend using pre-compiled headers. So, move all #include directives for standard headers (and other headers which are never going to change) to stdafx.h.
Include from the most specific to the least specific, starting with the corresponding .hpp for the .cpp, if one such exists. That way, any hidden dependencies in header files that are not self-sufficient will be revealed.
This is complicated by the use of pre-compiled headers. One way around this is, without making your project compiler-specific, is to use one of the project headers as the precompiled header include file.
Several separate considerations are conflated when deciding for a particular include order. Let try to me untangle.
1. check for self-containedness
Many answers suggest that the include order should act as a check that your headers are self-contained. That mixes up the consideration of testing and compilation
You can check separately whether your headers are self-included. That "static analysis" is independent of any compilation process. For example, run
gcc headerfile.h -fsyntax-only
Testing whether your header files are self-contained can easily be scripted/automated. Even your makefile can do that.
No offense but Lakos' book is from 1996 and putting those different concerns together sounds like 90s-style programming to me. That being said, there are ecosystems (Windows today or in the 90s?) which lack the tools for scripted/automated tests.
2. Readability
Another consideration is readability. When you look up your source file, you just want to easily see what stuff has been included. For that your personal tastes and preferences matter most, though typically you either order them from most specific to least specific or the other way around (I prefer the latter).
Within each group, I usually just include them alphabetically.
3. Does the include order matter?
If your header files are self-contained, then the include order technically shouldn't matter at all for the compilation result.
That is, unless you have (questionable?) specific design choices for your code, such as necessary macro definitions that are not automatically included. In that case, you should reconsider your program design, though it might work perfectly well for you of course.
It is a hard question in the C/C++ world, with so many elements beyond the standard.
I think header file order is not a serious problem as long as it compiles, like squelart said.
My ideas is: If there is no conflict of symbols in all those headers, any order is OK, and the header dependency issue can be fixed later by adding #include lines to the flawed .h.
The real hassle arises when some header changes its action (by checking #if conditions) according to what headers are above.
For example, in stddef.h in VS2005, there is:
#ifdef _WIN64
#define offsetof(s,m) (size_t)( (ptrdiff_t)&(((s *)0)->m) )
#else
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif
Now the problem: If I have a custom header ("custom.h") that needs to be used with many compilers, including some older ones that don't provide offsetof in their system headers, I should write in my header:
#ifndef offsetof
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif
And be sure to tell the user to #include "custom.h" after all system headers, otherwise, the line of offsetof in stddef.h will assert a macro redefinition error.
We pray not to meet any more of such cases in our career.
It seems on some software/compilers the pow() function works without any math libraries at all. Only with <iostream>. But in others it complains. Have math functions been added to the <iostream> library or to some other place?
Headers can - and often do - include other headers. Standard library headers are no exception to this.
Even though you chose not to include a header (let's name it a) that you depended on, it's possible that the header happened to be included by another header (let's name it b) that you did include. In that case, your program is not guaranteed to continue working if the b header is ever modified to not include a. That is why you must always include all headers that you depend on - even when your program appears to work without including some of them.
All different versions of different implementations of standard library are different and therefore a in one version could include b while a in another version could just as well not include b. Same applies to all API that have multiple versions of implementations.
As it is explicitly noted in here, pow IS in cmath header. http://www.cplusplus.com/reference/cmath/pow/.
What's for includes in <iostream>, just checked that current version of GCC(I'm using archlinux, so it's the latest) doesn't include cmath into any of iostream's inner includes.
Anyway, even if it works, it is against the standard. Include <cmath> explicitly.
I'm working on a C++ library project. I need to include a platform specific header to get access to some #defines. The catch is, I only want the platform's header visible within my my header. For those including my header, I don't want them to see the additional symbols.
I thought about using a C++ namespace to contain/control the symbol visibility, but it does not work (confer, #define statements within a namespace). And as far as I know, options like --exclude-libs,all only applies to library symbols at link time, and not header symbols.
I also thought about using the symbols I need from the platform header, and then undefining all the symbols it includes. But I don't know how to wildcard #undef platform_header.h/*.
There's a similar question at Including a header file into a header file without exposing it's content to the includer. He's doing it to limit IDE auto-completion, which is producing different answers than I need because of different requirements.
How can I limit the visibility of an included platform header to just my library header?
You can't, in general, avoid macro name pollution. The only tool at your disposal is the compiler firewall, to include the C (or just troublesome) header in an implementation file. You then provide your own C++ interface to that, in your header file.
I have question about the include of iostream when I use Xcode.
After the include of iostream, it seems that stdlib.h is also included automatically because when I write "merg",the Code Completion of Xcode gives me the function "mergesort" which is a function in the stdlib.h according to the documentation of Xcode. But I haven't included stdlib.h explicitely. So I guess it is the include of iostream that caused the include of stdlib.h. Any one could tell me why?
According to the C standard, stdlib.h doesn't have any function like mergesort, why in Xcode, the stdlib.h has such a function? Does it mean that the stdlib.h in Xcode is not a standard one?
How can I get a map of the dependency of every header file, for exemple, for a header file example.h, how can I know which other .h files are included in this exemple.h, and which other .h files include in themselves the file exemple.h.
Sorry for this long question, thank you very much for your answers!
In short: it's implementation-defined.
Which means it depends on the particular standard library implementation. The standard explicitly allows standard library headers to include other standard library headers (or at least define the symbols in them); C++11 17.6.5.2/1:
A C++ header may include other C++ headers. A C++ header shall provide the declarations and definitions
that appear in its synopsis. A C++ header shown in its synopsis as including other C++ headers shall provide
the declarations and definitions that appear in the synopses of those other headers.
To keep your code portable (even if only between versions of the same compiler/standard library), you should follow these rules:
Don't rely on transitive includes. Always explicitly include all the headers you need.
Don't be surprised by transitive includes. They're legal.
Any one could tell me why?
Presumably, something in your implementation of iostream needs something from stdlib.h. Standard headers are allowed to include other standard headers if they need them; and, since many headers contain inline function definitions, they will need the headers for anything used by those functions.
why in Xcode, the stdlib.h has such a function?
It's a BSD extension to the standard library.
Does it mean that the stdlib.h in Xcode is not a standard one?
It does indeed.
How can I get a map of the dependency of every header file, for exemple, for a header file example.h, how can I know which other .h files are included in this exemple.h, and which other .h files include in themselves the file exemple.h.
Most compilers can output the dependencies of a translation unit. For example, GCC has a -M option to do that.
What order should include files be specified, i.e. what are the reasons for including one header before another?
For example, do the system files, STL, and Boost go before or after the local include files?
I don't think there's a recommended order, as long as it compiles! What's annoying is when some headers require other headers to be included first... That's a problem with the headers themselves, not with the order of includes.
My personal preference is to go from local to global, each subsection in alphabetical order, i.e.:
h file corresponding to this cpp file (if applicable)
headers from the same component,
headers from other components,
system headers.
My rationale for 1. is that it should prove that each header (for which there is a cpp) can be #included without prerequisites (terminus technicus: header is "self-contained"). And the rest just seems to flow logically from there.
The big thing to keep in mind is that your headers should not be dependent upon other headers being included first. One way to insure this is to include your headers before any other headers.
"Thinking in C++" in particular mentions this, referencing Lakos' "Large Scale C++ Software Design":
Latent usage errors can be avoided by ensuring that the .h file of a component parses by itself – without externally-provided declarations or definitions... Including the .h file as the very first line of the .c file ensures that no critical piece of information intrinsic to the physical interface of the component is missing from the .h file (or, if there is, that you will find out about it as soon as you try to compile the .c file).
That is to say, include in the following order:
The prototype/interface header for this implementation (ie, the .h/.hh file that corresponds to this .cpp/.cc file).
Other headers from the same project, as needed.
Headers from other non-standard, non-system libraries (for example, Qt, Eigen, etc).
Headers from other "almost-standard" libraries (for example, Boost)
Standard C++ headers (for example, iostream, functional, etc.)
Standard C headers (for example, cstdint, dirent.h, etc.)
If any of the headers have an issue with being included in this order, either fix them (if yours) or don't use them. Boycott libraries that don't write clean headers.
Google's C++ style guide argues almost the reverse, with really no justification at all; I personally tend to favor the Lakos approach.
I follow two simple rules that avoid the vast majority of problems:
All headers (and indeed any source files) should include what they need. They should not rely on their users including things.
As an adjunct, all headers should have include guards so that they don't get included multiple times by over-ambitious application of rule 1 above.
I also follow the guidelines of:
Include system headers first (stdio.h, etc) with a dividing line.
Group them logically.
In other words:
#include <stdio.h>
#include <string.h>
#include "btree.h"
#include "collect_hash.h"
#include "collect_arraylist.h"
#include "globals.h"
Although, being guidelines, that's a subjective thing. The rules on the other hand, I enforce rigidly, even to the point of providing 'wrapper' header files with include guards and grouped includes if some obnoxious third-party developer doesn't subscribe to my vision :-)
To add my own brick to the wall.
Each header needs to be self-sufficient, which can only be tested if it's included first at least once
One should not mistakenly modify the meaning of a third-party header by introducing symbols (macro, types, etc.)
So I usually go like this:
// myproject/src/example.cpp
#include "myproject/example.h"
#include <algorithm>
#include <set>
#include <vector>
#include <3rdparty/foo.h>
#include <3rdparty/bar.h>
#include "myproject/another.h"
#include "myproject/specific/bla.h"
#include "detail/impl.h"
Each group separated by a blank line from the next one:
Header corresponding to this cpp file first (sanity check)
System headers
Third-party headers, organized by dependency order
Project headers
Project private headers
Also note that, apart from system headers, each file is in a folder with the name of its namespace, just because it's easier to track them down this way.
I recommend:
The header for the .cc module you're building. (Helps ensure each header in your project doesn't have implicit dependencies on other headers in your project.)
C system files.
C++ system files.
Platform / OS / other header files (e.g. win32, gtk, openGL).
Other header files from your project.
And of course, alphabetical order within each section, where possible.
Always use forward declarations to avoid unnecessary #includes in your header files.
I'm pretty sure this isn't a recommended practice anywhere in the sane world, but I like to line system includes up by filename length, sorted lexically within the same length. Like so:
#include <set>
#include <vector>
#include <algorithm>
#include <functional>
I think it's a good idea to include your own headers before other peoples, to avoid the shame of include-order dependency.
This is not subjective. Make sure your headers don't rely on being #included in specific order. You can be sure it doesn't matter what order you include STL or Boost headers.
First include the header corresponding to the .cpp... in other words, source1.cpp should include source1.h before including anything else. The only exception I can think of is when using MSVC with pre-compiled headers in which case, you are forced to include stdafx.h before anything else.
Reasoning: Including the source1.h before any other files ensures that it can stand alone without it's dependencies. If source1.h takes on a dependency on a later date, the compiler will immediately alert you to add the required forward declarations to source1.h. This in turn ensures that headers can be included in any order by their dependants.
Example:
source1.h
class Class1 {
Class2 c2; // a dependency which has not been forward declared
};
source1.cpp
#include "source1.h" // now compiler will alert you saying that Class2 is undefined
// so you can forward declare Class2 within source1.h
...
MSVC users: I strongly recommend using pre-compiled headers. So, move all #include directives for standard headers (and other headers which are never going to change) to stdafx.h.
Include from the most specific to the least specific, starting with the corresponding .hpp for the .cpp, if one such exists. That way, any hidden dependencies in header files that are not self-sufficient will be revealed.
This is complicated by the use of pre-compiled headers. One way around this is, without making your project compiler-specific, is to use one of the project headers as the precompiled header include file.
Several separate considerations are conflated when deciding for a particular include order. Let try to me untangle.
1. check for self-containedness
Many answers suggest that the include order should act as a check that your headers are self-contained. That mixes up the consideration of testing and compilation
You can check separately whether your headers are self-included. That "static analysis" is independent of any compilation process. For example, run
gcc headerfile.h -fsyntax-only
Testing whether your header files are self-contained can easily be scripted/automated. Even your makefile can do that.
No offense but Lakos' book is from 1996 and putting those different concerns together sounds like 90s-style programming to me. That being said, there are ecosystems (Windows today or in the 90s?) which lack the tools for scripted/automated tests.
2. Readability
Another consideration is readability. When you look up your source file, you just want to easily see what stuff has been included. For that your personal tastes and preferences matter most, though typically you either order them from most specific to least specific or the other way around (I prefer the latter).
Within each group, I usually just include them alphabetically.
3. Does the include order matter?
If your header files are self-contained, then the include order technically shouldn't matter at all for the compilation result.
That is, unless you have (questionable?) specific design choices for your code, such as necessary macro definitions that are not automatically included. In that case, you should reconsider your program design, though it might work perfectly well for you of course.
It is a hard question in the C/C++ world, with so many elements beyond the standard.
I think header file order is not a serious problem as long as it compiles, like squelart said.
My ideas is: If there is no conflict of symbols in all those headers, any order is OK, and the header dependency issue can be fixed later by adding #include lines to the flawed .h.
The real hassle arises when some header changes its action (by checking #if conditions) according to what headers are above.
For example, in stddef.h in VS2005, there is:
#ifdef _WIN64
#define offsetof(s,m) (size_t)( (ptrdiff_t)&(((s *)0)->m) )
#else
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif
Now the problem: If I have a custom header ("custom.h") that needs to be used with many compilers, including some older ones that don't provide offsetof in their system headers, I should write in my header:
#ifndef offsetof
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif
And be sure to tell the user to #include "custom.h" after all system headers, otherwise, the line of offsetof in stddef.h will assert a macro redefinition error.
We pray not to meet any more of such cases in our career.