当包含 .h 文件时,是否包含在 .cpp 文件中

Gid*_*pta -7 c++

所以可以说我有一堆这样命名的文件:

  • main.cpp : 包含 main() 函数
  • foo.h : 一些资源的声明
  • foo.cpp : 中声明的资源的定义 foo.h
  • goo.h : 其他资源的声明

现在foo.cpp包括goo.h

// foo.cpp

#include "goo.h"
//...
//...
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果我包含foo.hmain.cpp文件中,可以访问我的定义在goo.h我的main.cpp文件?或者我需要包括goo.hmain.cpp

// main.cpp
#include "foo.h"

int main() {
  // Can i access the definitions in goo.h here without including goo.h??
}
Run Code Online (Sandbox Code Playgroud)

如果您需要进一步说明,请告诉我。蒂亚!

eer*_*ika 7

如果我在 main.cpp 文件中包含 foo.h,我可以在我的 main.cpp 文件中访问 goo.h 中的定义吗?

取决于foo.h包含什么。如果包含goo.h,那么您可以在技术上访问main.cpp. 包含是一个传递性的“操作”。如果cincludebbincludes a,则间接c包含a

如果foo.h不包括goo.h(直接或间接),则没有理由包括foo.h会导致goo.h被包括。

当包含 .h 文件时,是否包含在 .cpp 文件中

不。

虽然包含是可传递的,但它不是对称的。foo.cpp包括foo.h,但foo.h不包括foo.cpp


请注意,依赖于可传递包含的标头中的定义/声明通常是一种不好的做法。

或者我需要在 main.cpp 中包含 goo.h?

如果main.cpp您依赖于 的定义/声明goo.h,那么您应该包含goo.hmain.cpp.