C++多文件编译过程
我正在尝试最大限度地减少项目中的标头包含,最大限度地使用前向声明,并且需要弄清楚 C++ 编译过程到底是如何工作的。
它从main.cpp开始,我们在其中分配对象A,因此我们包含Ah类A使用类B和C,所以我包含Bh和Ch现在如果我想在main.cpp中分配B,编译将失败。
我可以轻松地将 Bh 包含在 main.cpp 中,但我想知道它是否真的有必要,因为我已经包含了 Ah 并且在 Ah 中包含了 Bh 我读了一些关于这个主题的先前讨论,其中有一些关于递归的内容并重新编译源文件。那么这究竟是如何运作的呢?
感谢您的任何建议。 :)
i'm trying to minimize header inclusion in a project, maximizing the usage of forward declarations and need to get clear on how exactly the process of C++ compilation works.
It starts of with main.cpp where we allocate object A, therefore we include A.h. Class A uses classes B and C, so i include B.h and C.h. Now if I wanted to allocate B in main.cpp, the compilation would fail.
I can easily include B.h in main.cpp, but I'm wondering if its really necessary, because I'm already including A.h and in A.h I'm including B.h. I read some previous discussions on this topic, where there was something about recursion and recompilation of the source file. So how does that exactly work?
Thanks for any advice. :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
作为一个简单的经验法则,只要需要对齐、接口或大小,您就需要定义符号。如果标头仅将类型作为指针引用,则只需声明它。
所有引用标头的编译单元都必须独立地完成理解它的步骤。这就是为什么标头中的代码会超线性地增加编译时间。
如果您感兴趣,您可以准确地了解预处理器为编译器准备的内容。 GCC 具有以下语法。
MSVC 有类似的功能,但我不能引用它。
我想这是一个情况问题。省略标头的主要烦恼是,通常发生的情况是其他人更改了代码库不同部分中的某些内容,并且您必须猜测为什么在从源代码管理更新时缺少符号。本质上,您在根本不明确的标头之间创建了依赖关系。
如果我的想法是合法的,您可以将包含内容添加到空 cpp 文件中的任何标头中,然后它就会编译。我不明白为什么你不希望这样做,尽管我不准备捍卫它在所有情况下都是正确的做法。
As a simple rule of thumb, you need to define symbols any time their alignment, interface, or size is required. If a header only refers to a type as a pointer, you only need to declare it.
All compilation units which reference a header have to go through the paces of understanding it independently. That is why code in a header increases compile times super-linearly.
You can see exactly what the preprocessor prepares for the compiler if you are interested. GCC has the below syntax.
MSVC has similar functionality, though I cannot quote it.
This is a matter of circumstance, I suppose. The major annoyance with omitting headers, is that usually what happens is someone else changes something in a disparate part of the code base and you have to guess at why you are missing symbols when you update from source control. Essentially you create dependencies between headers that are not clear at all.
If my whims were law, you could throw an include to any header in an empty cpp file and it would just compile. I don't see why you wouldn't want that, though I'm not prepared to defend it as the right thing to do in all situations.