How does chain of includes function in C++?

孤街浪徒 提交于 2021-01-28 23:14:16

问题


  • In my first.cpp I put #include second.h.
    As a consequence first.cpp sees the content of second.cpp.
  • In second.cpp I put #include third.h.

My question is: will first.cpp see the content of the third.cpp?

ADDED

I thought that if I include second.h I will be able to use functions declared in second.h and described (defined, written) in the second.cpp. In this sense the content of the second.cpp becomes available to the first.cpp


回答1:


You can think about #include as a simple text insert. But if you include second.h you "see" second.h and not second.cpp.




回答2:


When using #include the actual file content of that file appears as part of the input for the compiler. This means that first.cpp will appear to the compiler as if it has second.h and third.h inside it. The source code in second.cpp and third.cpp are separate files [1], that need to be compiled separately, and they are all combined at the linking stage at the end of compilation.

[1] unless second.h contains #include "second.cpp"or something to that effect - this is not typically how to do this, however, so I'm going to ignore that option.




回答3:


With a concrete example

//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
}

The cpp file that includes a header file sees what's in the header file, not in other source files that include the header.




回答4:


first.cpp will see the constent of third.h (and you will be able to use in first.cpp functions declared in third.h and defined in third.cpp). Suppose, you have in your test.h:

#include<iostream>
using namespace std;

and in your test.cpp:

#include "test.h"

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

As you see, cout declared in <iostream> is visible in test.cpp.



来源:https://stackoverflow.com/questions/18270814/how-does-chain-of-includes-function-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!