头文件的相互包含
假设我有一个名为 inclusions.h
的头文件,其中包含我的项目的所有 #include <...>
。 inclusions.h
包含另一个名为 settings.h
的头文件,其中可以修改各种常量。
如果 inclusions.h
中包含 #include
,settings.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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果 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.
这取决于内含物的顺序。
#include
是一个预处理器指令,仅通过文本替换来工作。因此,如果在inclusions.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 ininclusions.h
you have:settings "can see" math. If you have:
it can't. But: what would happen if you used
settings.h
elsewhere without includingmath.h
before? So in the end, try to make each include file independent.在这种情况下,正如其他人所指出的,根据包含的顺序,它可以被访问。这是因为这些源文件是一个翻译单元的一部分(源 + 本质上包括),因此如果
出现在"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.