C++頭文件為什么要加#ifndef #define #endif


#ifndef 在頭文件中的作用

在一個大的軟件工程里面,可能會有多個文件同時包含一個頭文件,當這些文件編譯鏈接成一個可執行文件時

,就會出現大量“重定義”的錯誤。在頭文件中實用#ifndef #define #endif能避免頭文件的重定義。

方法:例如要編寫頭文件test.h

在頭文件開頭寫上兩行:

#ifndef _TEST_H

#define _TEST_H                 //一般是文件名的大寫

頭文件結尾寫上一行:

#endif

這樣一個工程文件里同時包含兩個test.h時,就不會出現重定義的錯誤了。

分析:當第一次包含test.h時,由於沒有定義_TEST_H,條件為真,這樣就會包含(執行)#ifndef _TEST_H和

#endif之間的代碼,當第二次包含test.h時前面一次已經定義了_TEST_H,條件為假,#ifndef _TEST_H和

#endif之間的代碼也就不會再次被包含,這樣就避免了重定義了。

 

#include "test.h"

#include "debug.h"

 

如果 debug.h 內代碼如下

#include "a.h"

#include "test.h"

這樣就重復包含了 “test.h”

 

如果 test.h 定義時 使用 #ifndef #define #endif 語句可以防止重復包含,

當第一次包含test.h時,由於沒有定義_TEST_H,條件為真,這樣就會包含(執行)#ifndef _TEST_H和

#endif之間的代碼,當第二次包含test.h時前面一次已經定義了_TEST_H,條件為假,#ifndef _TEST_H和

#endif之間的代碼也就不會再次被包含,這樣就避免了重定義了。

主要防止頭文件里的全局變量重復定義,建議不要在頭文件里定義變量。

 

問題:

#include “test.h” 編譯器執行了哪些操作??? 

能否通過調試看到#include的過程和效果呢?

#include "hello.h"

包含頭文件,實際是一個復制 粘貼的過程,把頭文件中的所有內容復制到當前文件中。

 

Logically, that copy/paste is exactly what happens. I'm afraid there isn't any more to it. You don't need the ;, though.

 

Your specific example is covered by the spec, section 6.10.2 Source file inclusion, paragraph 3:

 

A preprocessing directive of the form

# include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters.

 

https://www.cnblogs.com/xuepei/p/4027946.html

https://www.cnblogs.com/hello-Huashan/p/5545244.html

https://stackoverflow.com/questions/5735379/what-does-include-actually-do

 

“頭文件被重復引用”是什么意思?

答:其實“被重復引用”是指一個頭文件在同一個cpp文件中被include了多次,這種錯誤常常是由於include嵌套造成的。

比如:存在a.h文件#include "c.h",而b.cpp文件同時#include "a.h" 和#include "c.h",此時就會造成c.h被b.cpp重復引用。

感覺這句話有問題呢??

我的理解,不確定對不對:

 

如果使用宏定義寫法:

// b.cpp
#include "a.h" // 執行,包含c.h,導致定義C_H #include "c.h" // 執行,包含c.h,因為上一行已經定義了C_H,所以條件為假,#define一下的代碼沒有執行
// a.h
#ifndef A_H
#define A_H

#include "c.h"

#endif
// c.h
#ifndef C_H
#define C_H

//pass

#endif

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM