在c++中包含头文件
Include header files in c++
我手头的c++入门版并没有说太多我要问的问题,这是我在谷歌上搜到的链接:
当编译器编译#include "example.h"行时,它将example.h的内容复制到当前文件中。
那么,如果这是真的,在下面的例子中为什么B.h不知道A.h ?是文件的编译方式吗?我是否必须在每个使用它的文件中包含A.h然后在使用这些文件的程序。h中包含每个使用A.h的文件?
In program.h
#include "A.h"
#include "B.h"
警告:非常糟糕的代码:
a.h
#ifndef A_H
#define A_H
#define SOME_LIT "string lit in A.h"
#endif
b.h
#ifndef B_H
#define B_H
#include <iostream>
void foo() { std::cout << SOME_LIT << 'n'; }
#endif
main.cpp
#include "a.h"
#include "b.h"
int main()
{
foo();
}
打印:
$ ./a.out
string lit in A.h
可见b.h
知道a.h
中的define
。如果您忘记了#include "a.h"
,或者将其放在 #include "b.h"
下面,则会中断。但是,作为一般规则,您应该在任何需要的文件中显式地#include
头文件。这样你就知道你只关心main
中的foo
,所以你只需要#include
foo
的头,也就是b.h
:
#include "b.h"
int main()
{
foo();
}
相关文章:
- 使用mongocxx驱动程序时包含头文件问题
- 如何为包含头文件的目标编写生成文件?
- 如何在 CMakeLists.txt Qt Creator 中包含头文件?
- 当包含头文件的文件不在根项目文件夹中时,如何包含它
- 在生成文件先决条件中包含头文件的原因
- My Project的属性配置正确,但Visual Studio仍然无法打开包含头文件
- 在 PostgreSQL C 扩展中包含头文件
- 是否可以在C++中以间接方式包含头文件
- 是否需要包含头文件?
- 如何在不包含完整的文件系统头的情况下使用文件系统的类路径C++17?
- 我收到未声明的标识符错误,但我已包含头文件?
- 为什么我们需要构建一个提升库,仅仅包含头文件还不够吗,因为提升是模板
- C++:当顺序真正重要时,如何保证在项目中包含头文件的顺序
- 如何在C++中包含头文件时错误地重载
- 我在C++中无效使用不完整的类型类错误,如何正确包含头文件?
- 虚幻引擎4.16,C++包含头文件
- C++多次包含头文件
- 令牌之前的预期类名 '{' - 包含头文件和 CPP 文件
- 可以将标头文件包含在多个源文件中,而无需重复保护
- 有条件地将文件包含在C++标头中