簡體   English   中英

在C ++中包含頭文件

[英]Include header files in c++

我要問的C ++ Premier話不多,這就是我在Google上搜索LINK的意思

當編譯器編譯#include“ example.h”行時,它將example.h的內容復制到當前文件中。

因此,如果是這樣,在下面的示例中,為什么Bh不了解Ah? 文件是如何編譯的? 我是否必須在使用它的每個文件中都包含Ah,然后在使用這些文件的program.h中包含每個使用Ah的文件?

In program.h
#include "A.h"
#include "B.h"

警告:非常錯誤的代碼:

ah

#ifndef A_H
#define A_H

#define SOME_LIT "string lit in A.h"

#endif

bh

#ifndef B_H
#define B_H

#include <iostream>

void foo() { std::cout << SOME_LIT << '\n'; }

#endif

main.cpp

#include "a.h"
#include "b.h"

int main()
{
    foo();
}

打印:

$ ./a.out 
string lit in A.h

因此,您可以看到bh了解ahdefine 如果您忘記了#include "ah"或將其放在 #include "bh" 下面 ,則可能會中斷。

但是,作為一般規則,您應該在需要的任何文件中明確#include一個標頭。 這樣,您就知道只關心main foo ,因此只需#include foo標頭,即bh

#include "b.h"
int main()
{
    foo();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM