在C
和C++
編程語言,一個#include
後衛,有時也被稱爲macro guard
,是使用打交道時避免double inclusion
問題的特定構造包含指令。將#include警衛添加到頭文件是使該文件具有冪等性的一種方法。例如,考慮在child.h
文件中包含grandfather.h
和father.h
頭文件。
文件 「grandfather.h」
#ifndef GRANDFATHER_H
#define GRANDFATHER_H
struct foo {
int member;
};
#endif /* GRANDFATHER_H */
文件 「father.h」
#include "grandfather.h"
文件 「child.c」
#include "grandfather.h"
#include "father.h"
這裏,第一個包含"grandfather.h"
會導致定義宏GRANDFATHER_H
。然後,當「child.c」第二次包含「grandfather.h」(因爲father.h
還包括grandfather.h
),則包括father.h
,#ifndef
測試返回false,並且預處理器跳到文件grandfather.h
的#endif,從而避免struct foo的第二個定義。程序編譯正確。
可能的重複[爲什麼#ifndef和#define在C++頭文件中使用](http://stackoverflow.com/questions/1653958/why-are-ifndef-and-define-used-in-c-header - 文件)編輯:這個問題最初也是用C++標記的。就我所知,這個問題的答案與C++和c相同,並且已經在重複中得到了答案。 – user2079303
嗯,我打電話給那些未定義的行爲 – user3528438
@ user3528438,你基於什麼調用那些未定義的行爲? – StoryTeller