为什么要先包含相关标头? [英] Why include related header first?

查看:60
本文介绍了为什么要先包含相关标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于问题 C/C ++包含文件顺序/最佳做法,最佳答案建议首先包含相关标头.

On the question C/C++ include file order/best practices, the best answer recommends to include the related header first.

Google 但是,在这两种情况下,我都找不到您为什么要这样做的充分理由.

However, in both cases, I couldn't find a good reason why you would do this.

Google和Mozilla编码规则对我来说看起来最好,因为它们会强制您首先包含最标准"的标头.

Google and Mozilla coding rules look best to me, because they enforce you to include the most "standard" headers first.

这样,我认为您不太可能弄乱包含的文件(例如,通过未定义其他标头中使用的某些宏等),因此这似乎是我的最佳选择.

This way, I think you are less likely to mess up the included files (for examples by undefining some macros used in the other headers etc.) so that looks like the best way to go for me.

但是按照这个原理,为什么要先包含相关的标头?由于其中的任何语法错误都可能使以下所有标头混乱?

But following that rationale, why would you include the related header first? Since any syntax error in it might mess all the following headers?

我认为最好在最后包含相关标头.

I would think including the related header last would be best instead.

推荐答案

这是为了确保您的客户在包含您的库标头时不会讨厌您.

It's to make sure your clients don't hate you when they include your library header.

如果标头易碎并且会因错误的包含顺序而中断,则它似乎不是在您的环境中就可以正常使用的原因-因为您包含了 所需的标头-但无法编译客户端代码.因为可能一点都不明显,还需要插入其他标头才能使其正常工作.

If the header is brittle and subject to break on wrong inclusion order, it may appear to work in your environment when it isn't first - since you include the headers you need - but fail to compile for client code. Because it may not at all be obvious what other headers need to be pulled in for it to work.

首先包括与当前实现文件相对应的标头,用于检查标头是否是自包含的.自给自足不仅仅包括必要的标头.它还需要为您在API中使用的类型添加所需的前向声明.自然,如果您在其前面包含该类型的标头,则标头将编译,但您可能不希望将其引入,因为您仅依赖于API中的类型名称.

Including first the header which corresponds to the current implementation file goes toward checking that the header is self-contained. Self-containment goes beyond just including the necessary headers. It also entails adding the required forward declarations for types you use in your API. Naturally your header will compile if you include the header for the type before it, but you may not wish to pull it in since you only depend on the type name in your API.

某些样式指南禁止前向声明,因此这些声明可能不构成其构成的基本原理.

Some style guides prohibit forward declarations, so those may not be part of the rationale they pose.

这篇关于为什么要先包含相关标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆