【问题标题】:How does chain of includes function in C++?包含链在 C++ 中如何起作用?
【发布时间】:2013-08-16 19:13:38
【问题描述】:
  • 在我的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 可用

【问题讨论】:

  • 为什么first.cpp 会看到second.cpp 的内容?
  • first.cpp 将“看到”您在 second.h 中输入的任何内容,不多也不少。

标签: c++ include dependencies


【解决方案1】:

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

【讨论】:

  • 我认为如果我包含second.h,我将能够使用在second.h 中声明并在second.cpp 中描述(定义、编写)的函数。从这个意义上说,second.cpp 的内容可供first.cpp 使用
  • @Roman 不是内容,而是声明。这意味着 first.cpp 看到函数(因为它们是在 .h 文件中声明的),但它实际上并不关心实现(通常倾向于在 .cpp 文件中)。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    举个具体的例子

    //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 文件会看到头文件中的内容,而不是包含头文件的其他源文件中的内容。

    【讨论】:

      【解决方案4】:

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

      #include<iostream>
      using namespace std;
      

      在你的 test.cpp 中:

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

      如您所见,&lt;iostream&gt; 中声明的cout 在 test.cpp 中可见。

      【讨论】:

      • 你确定不会编译吗?
      • 它不会这样编译:g++ test.cpp -o test
      • @doctorlove:它确实可以编译! # 在“test.h”中丢失。
      猜你喜欢
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      • 2016-02-17
      • 2013-07-04
      • 2014-05-15
      • 1970-01-01
      相关资源
      最近更新 更多