问题
- In my
first.cpp
I put#include second.h
.
As a consequencefirst.cpp
sees the content ofsecond.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