头文件的相互包含

发布于 2024-10-03 00:41:36 字数 361 浏览 4 评论 0原文

假设我有一个名为 inclusions.h 的头文件,其中包含我的项目的所有 #include <...>inclusions.h 包含另一个名为 settings.h 的头文件,其中可以修改各种常量。

如果 inclusions.h 中包含 #includesettings.h 也可以访问数学库吗?或者我是否也必须在 settings.h#include

Let's say I have a header file called inclusions.h that has all the #include <...>s for my project. inclusions.h includes another header file called settings.h, where various constants can be modified.

If #include <math.h> in inclusions.h, will settings.h have access to the math library as well? Or do I have to #include <math.h> in settings.h as well?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无远思近则忧 2024-10-10 00:41:36

如果 math.h 包含在 settings.h 之前,则 settings.h 也应该有权访问 math.h。但为了确保访问(并指示依赖性),您应该在需要的地方包含这些文件,在 math.h 中也是如此。

If math.h is included before settings.h, settings.h should also have access to math.h. But to ensure the access (and to indicate the dependencies), you should include the files where they are needed, so also in math.h.

花开雨落又逢春i 2024-10-10 00:41:36

这取决于内含物的顺序。 #include 是一个预处理器指令,仅通过文本替换来工作。因此,如果在 inclusions.h 中您有:

#include <math.h>
#include <settings.h>

设置“可以看到”数学。如果你有:

#include <settings.h>
#include <math.h>

它不能。但是:如果您之前在其他地方使用了 settings.h 而没有包含 math.h ,会发生什么情况?所以最后尽量让每个包含文件独立。

It depends on the order of the inclusions. #include is a preprocessor directive that simply works by textual substitution. So, if in inclusions.h you have:

#include <math.h>
#include <settings.h>

settings "can see" math. If you have:

#include <settings.h>
#include <math.h>

it can't. But: what would happen if you used settings.h elsewhere without including math.h before? So in the end, try to make each include file independent.

同尘 2024-10-10 00:41:36

在这种情况下,正如其他人所指出的,根据包含的顺序,它可以被访问。这是因为这些源文件是一个翻译单元的一部分(源 + 本质上包括),因此如果 出现在 "settings.h" 之前,则可以通过它查看。但是,如果设置成为另一个翻译单元的一部分,或者您决定移动某些包含内容,则可能会发生变化。为了“安全”,您应该只包含文件中所需的任何头文件。

In this case, as others have noted, depending on the order of inclusion it could be accessible. This is because those source files are a part of one translation unit (source + includes essentially) so if <math.h> comes before "settings.h", it could be viewable by it. However, if settings became a part of another translation unit, or if you decided to move certain includes around that could change. To be "safe", you should just included whatever header files which are necessary for a file to have in that file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文