簡體   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