在c++中包含头文件

Include header files in c++

本文关键字:文件 包含头 c++      更新时间:2023-10-16

我手头的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();
}