繁体   English   中英

C ++中包含链的功能如何?

[英]How does chain of includes function in C++?

  • 在我的first.cpp我放了#include second.h
    因此, first.cpp看到second.cpp的内容。
  • second.cpp我放#include third.h

我的问题是:将first.cpp看到的内容third.cpp

添加

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

您可以将#include视为简单的文本插入。 但是如果你包含second.h你会“看到” second.h而不是second.cpp

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

[1]除非second.h包含#include "second.cpp"或类似的东西 - 但这通常不是如何做到这一点,所以我将忽略该选项。

first.cpp将看到third.h的含义(并且您将能够在third.hpp中声明并在third.cpp中定义的first.cpp函数中使用)。 假设,你在test.h中:

#include<iostream>
using namespace std;

在你的test.cpp中:

#include "test.h"

int main()
{
    cout << "Hello world!" << endl; 
}

如您所见,在<iostream>声明的cout在test.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文件可以查看头文件中的内容,而不是包含头文件的其他源文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM