简体   繁体   English

了解 STL 包括以及编译/预处理的工作原理

[英]Understanding STL includes and how the compilation/preprocessing works

I was investigating STL implementations, and I'm failing to understand how the code compiles.我正在调查 STL 实现,但我无法理解代码是如何编译的。

Take std::set as an example.std::set为例。 Here's a reference to libstdc++ on github. . 这里引用 github 上的 libstdc++。。

Internally, std::set uses a red-black tree, using class _Rb_tree , lines 131-133.在内部, std::set使用红黑树,使用class _Rb_tree ,第 131-133 行。

It appears class _Rb_tree is defined in stl_tree.h, available here , line 425.看起来class _Rb_tree在 stl_tree.h 中定义,可在此处获取,第 425 行。

I'm confused because stl_set.h does not include stl_tree.h .我很困惑,因为stl_set.h不包括stl_tree.h Why does this not fail?为什么这不会失败?

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.如果您查看实际公开并打算使用的 header <set> ,您可以看到stl_tree.h包含在stl_set.h之前,因此包含主要 header 的文件将毫无问题地编译。

It does not fail, because you are looking at implementation details and you arent supposed to include stl_set.h directly.它不会失败,因为您正在查看实现细节并且您不应该直接包含stl_set.h You do include <set> which does include both of those headers.您确实包含了<set> ,其中确实包含了这两个标头。

I suppose you are confused because typically a header includes what it uses.我想您很困惑,因为通常 header 包含它使用的内容。 That way one can make sure there are no hidden dependencies.这样就可以确保没有隐藏的依赖关系。 Including that one header is sufficient to use it.加上那个header就够用了。

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:如果你遇到这种情况,那么你应该写第三个 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.现在您的代码的用户可以包含foobar.h而不必担心包含的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM