Which Headers in the C++ Standard Library Are Guaranteed to Include Another Header

Where to put my standard library headers when creating classes in C++?

According to the C++ standard:

A translation unit is the basic unit of compilation in C++. It
consists of the contents of a single source file, plus the contents of
any header files directly or indirectly included by it, minus those
lines that were ignored using conditional preprocessing statements.

Note, the "indirectly included" wording. Any header to #include in another header is included in any source file that #includes that header. So if you require it to be included in the header, that is if your header requires a definition not simply a declaration, #include it there.

A small of example of how a translation unit is generated: Initially we have our header. Let's call it stdfoo.h (this is an example, you should avoid naming your own headers with std to avoid collision.)

#ifndef STD_FOO_ // here is our header guard
#define STD_FOO_

typedef long howl_t;
void foo();

#endif // STD_FOO_ close the header guard at the end

Let's include this in our project source main.cxx:

#include <stdfoo.h>

int main {
foo();
return 0;
};

When we compile this, it gets run through the preprocessor into a translation unit. Let's take a look at what that generated unit may look like:

typedef long howl_t;
void foo();

int main {
foo();
return 0;
};

The #include directive has expanded stdfoo.h in the translation unit so the compiler can look at the single translation unit and generate an object.

Let's change things up and give main.cxx a header, main.h.

#ifndef MAIN_H
#define MAIN_H

class BarkBark {
BarkBark() {}
void emit();
};

#endif // MAIN_H

Use it in our new main.cxx:

#include "main.h"
#include <stdfoo.h>

int main {
BarkBark woof;
woof.emit();
foo();
return 0;
};

The translation unit would look like:

class BarkBark {
BarkBark() {}
void emit();
};

typedef long howl_t;
void foo();

int main {
BarkBark woof;
woof.emit();
foo();
return 0;
};

Now say emit uses howl_t as an argument like so void emit(howl_t h) this would require either redeclaring howl_t, a dicey way to go, or including stdfoo.h in main.h

#ifndef MAIN_H
#define MAIN_H

#include <stdfoo.h>

class BarkBark {
BarkBark() {}
void emit(howl_t h);
};

#endif // MAIN_H

How does that translation unit look?

typedef long howl_t;
void foo();

class BarkBark {
BarkBark() {}
void emit();
};

int main {
howl_t aroooooo = 0;
BarkBark woof;
woof.emit(aroooooo);
return 0;
};

The preprocessor has expanded the #include inside of the #included header.

Note whether or not #include <stdfoo.h> remains in main.cxx the translation unit would look the same due to the preprocessor handling the header guards, the second inclusion is simply discarded.

Now, as far as standard library headers, most of not all standard libraries guard against multiple inclusion, so you can #include then as frequently and often as your heart desires with no ill effect. The resulting translation unit will only include it once for compilation. Do note this is not guaranteed with any other headers and including unguarded headers multiple times can yield very obscure looking errors as the duplicate declarations only exist in the translation unit.

So to answer your question, if your header requires a particular class or function to be included, #include it in the header. At that point, it is a stylistic choice whether you decide to #include it in the source file as well. Some say do in case the header changes, some say do not to simplify code. That choice is really up to you.

If a header is not required in another header file, you are much better off only including it in each source file that requires it so that your code produces smaller translation units for compilation and in order to reduce namespace pollution.

However! This is not a hard and fast rule. Some do it differently and arrange #includes into logical positions where they may be used or where certain headers are used in multiple source files to reduce code duplication. Personally, I think of this arrangement added technical debt if code may be improved or refactored down the line and headers become orphaned.

Should I include every header?

If you use a header related entity (e.g. some type) in a file, you should include the related header for it. Don't rely on headers to include each other. If you use it, include it.

The C++ standard library doesn't mandate inclusion of <string> in <vector> nor vice-versa. Trying to make use of functionality like this would limit the code to a specific implementation. In general, the standard library headers may or may not include other headers (or their own internal headers) in an unspecified order or manner. One notable exception is <initializer_list> which is required to be included in a few of the other standard headers. Changes to this unspecified order or manner can also happen, thus breaking previously compiling code with the updated compiler or an updated standard library implementation (this has been known to happen).

Also consider that if the header file is the definition for the class, then it should include what is required for the definition of that class. The associated .cpp should include its associated .h and the remaining files required to implement the class. Don't need it, don't include it; don't include more than needed (llvm style guide). One exception here is templates (that don't have an associated .cpp); this exception would apply to other header only implementations.

It is noted that maintenance of the include what you use can be difficult in the long run; thus it makes sense that it is important in the beginning of the coding cycle to include what is required for the interface; and then again to check the includes with any reasonable change that is made to the code.

There seems to be some progress w.r.t. tools in this regard, such as the iwyu project, that uses the clang tool chain and seems to have support for msvc as well.

One counter example would be if the reason for the header is to include other headers, then maybe, but even then I would be very careful - make sure it is clearly defined what it includes. An example of this could be a precompiled header.

How can I determine what header calls another header in c++?

You should always check the documentation for any symbol you use and include any headers it is specified to require.

The C++ standard only specifies which symbols must be made available when a standard header is included. It does not place any limits on what other symbols are made available. In your example, the standard specifies the <iostream> must include <ios>, <streambuf>, <istream>, and <ostream>, but <iostream> may include any other headers its authors want. It may also forward-declare any symbols it may need.

  1. (so should I trust that documentation, when the did not mentioned <string> header in "Includes" list of <iostream>?).

You should trust that the symbols specified as being available when you include <string> will be. That is all. You may not assume that those symbols will not be visible when including any other header.


  1. what calls what? And what is the "true" header, that define std::string of them? (is it /usr/include/c++/8/bits/basic_string.h?...)

This is an implementation detail that can only be answered by inspecting the implementation's headers. Libstdc++ (the standard library implementation used by GCC) has the declaration of the std::string class in bit/stringfwd.h and its definition in bits/basic_string.h and bits/basic_string.tcc (for the current version, at least), but that is not required at all. If the libstdc++ maintainers decided they wanted to refactor and reorganize things, they would be free to do so. The only requirement that is guaranteed by the C++ language is that std::string must be available when <string> is included.

But from the upper output of the "string headers", there is multiple of them, so how's possible for a compiler to compile only sometimes?

Different standard library implementations or different versions of the same implementation could transitively include different headers. Different compiler flags (i.e. a debug flag or different standard compliance mode) could transitively include different headers.

Which of these headers are really important for successful compilation?


  1. How to orient in cpp headers, which are meaningful for compiler, and could be tracked their "#include stack" (i.e. other meaningful headers)?

All of them are meaningful. The standard library's authors wouldn't include a header if they didn't need it for something. Just because you aren't using any symbols declared/defined in that header directly doesn't mean none are being used.



EDIT: If it depends on my specific implementation of my stdlib++, then I want to know how can I determine from source whether that inclusion is made before I try to compile. Not by "If it compiles, then it works".

The only way to know is to look at your standard library implementation's headers. There is nothing magical about them; they're just C++ code. If you want to know if <iostream> includes a declaration or definition of std::string, open your implementation's copy of <iostream> and look for a declaration or definition of std::string. Repeat this process for any headers that <iostream> includes.

Which C++ header includes which other headers?

C++ provides no guarantees in general for any sort of recursive inclusion. It is your responsibility to always include all headers that you need. Similarly, it does not guarantee that any particular standard library header is not included. (For example, your implementation could legally always include all standard library headers!) That's why-and-because everything is in the std namespace.

(I believe there's a special provision for the C library headers - I think you won't get names in the global namespace unless you explicitly include those headers.)

Some headers do have specific requirements; for example, in C++11 (but not before) it is required that <iostream> include both <ostream> and <istream>. But that's just one specific case.

Why do some LLVM standard library headers include other headers but GCC does not

For every function you use, consult the C++ reference to find out which header you should include.

The reference for fabs says that you have to include <cmath>.

Why don't Standard C Libraries need to be divided into a header and implementation file?

The standard C library has already been compiled into a library, which might be called something like libc.so or MSVCRT100.DLL. You can provide this file instead of the *.o or *.obj files that the compiler would generate from your *.c file. The compiler links this runtime library with every program silently and automatically.

This is how other libraries work, too. If you have the compiled OpenSSL library, you link to the library and #include the header file in your source code to see its interfaces, such as the function names and prototypes. You don't need the other source files that the library was built from.

You can download the source code to many implementations of the C library, such as GNU libc. The runtime is, in fact, implemented in *.c files, which you can read, modify, recompile and submit patches to the maintainers for, but it's compiled to a shared library ahead of time and your compiler links to that.



Related Topics



Leave a reply



Submit