Home > Back-end >  Understanding STL includes and how the compilation/preprocessing works
Understanding STL includes and how the compilation/preprocessing works

Time:12-01

I was investigating STL implementations, and I'm failing to understand how the code compiles.

Take std::set as an example. Here's a reference to libstdc on github..

Internally, std::set uses a red-black tree, using class _Rb_tree, lines 131-133.

It appears class _Rb_tree is defined in stl_tree.h, available here, line 425.

I'm confused because stl_set.h does not include stl_tree.h. Why does this not fail?

CodePudding user response:

If you look at the header that is actually exposed and meant to be used, <set>, you can see that stl_tree.h is included just before stl_set.h and so a file that includes that main header will compile without any issue.

CodePudding user response:

It does not fail, because you are looking at implementation details and you arent supposed to include stl_set.h directly. You do include <set> which does include both of those headers.

I suppose you are confused because typically a header includes what it uses. That way one can make sure there are no hidden dependencies. Including that one header is sufficient to use it.

However, thats just what is good practice / convention. Nothing (but conventions) forbids you to write two headers like this:

# foo.h
struct foo { bar b; }

# bar.h
struct bar {};

To use them one has to include both in the right order:

#include "bar.h"
#include "foo.h"

foo f;  // works !!

Of course you should not write headers like that when they are supposed to be included by other code. If you are in a situation like this then you should write a thrid header:

# foobar.h
#include "bar.h"
#include "foo.h"

And now users of your code can include foobar.h and need not worry about the order of includes.

  • Related