包含链在C++中是如何起作用的

How does chain of includes function in C++?

本文关键字:起作用 C++ 包含链      更新时间:2023-10-16
  • 在我的first.cpp中,我放置了#include second.h
    因此,CCD_ 3看到了CCD_ 4的内容
  • second.cpp中,我放置了#include third.h

我的问题是:first.cpp会看到third.cpp的内容吗?

添加

我认为,如果我包含second.h,我将能够使用second.h中声明的函数,并在second.cpp中描述(定义、编写)。从这个意义上讲,second.cpp的内容对first.cpp 来说是可用的

使用#include时,该文件的实际文件内容显示为编译器输入的一部分。这意味着first.cpp在编译器看来就像它里面有second.hthird.hsecond.cppthird.cpp中的源代码是单独的文件[1],需要单独编译,它们都在编译结束时的链接阶段组合在一起。

[1] 除非second.h包含#include "second.cpp"或类似的内容,否则这不是通常的方法,所以我将忽略该选项。

您可以将#include看作一个简单的文本插入。但如果包含second.h,则"看到"的是second.h,而不是second.cpp

以为例

//second.h
#ifndef SECOND_INCLUDED
#define SECOND_INCLUDED
void foo();
#endif


//first.cpp
#include second.h
void bar()
{
    foo();//ok 
}
void no_good()
{
    wibble();//not ok - can't see declaration from here
}


//third.h
#ifndef THIRD_INCLUDED
#define THIRD_INCLUDED
void wibble();
#endif


//second.cpp
#include second.h
#include third.h
void foo()
{
    wibble();//ok in second.cpp since this includes third.h
}

包含头文件的cpp文件查看头文件中的内容,而不是包含头的其他源文件中的信息。

first.cpp将看到third.h的常量(您将能够在third.h中声明并在third.cpp中定义的first.cpp函数中使用)

#include<iostream>
using namespace std;

在你的测试中。cpp:

#include "test.h"
int main()
{
    cout << "Hello world!" << endl; 
}

如您所见,在<iostream>中声明的cout在test.cpp中可见。