2012-03-13 51 views
0

假設我有a.h其中包括以下內容:預處理器的#ifndef

<stdbool.h> 
<stddef.h> 
<stdin.h> 

假設我也有b.h其中還包括<stdbool.h>。如果a.h在其中有#ifndef預處理器定義語句,並且b.h沒有。 a.h只會包含b.h中未包含的內容嗎?因此,當b.h包括a.h時,a.h將包括stddef.hstein.h而不是重新包含stdbool.h還是那些預處理器定義函數僅用於查看整個類是否被重新定義,而不是其中的特定函數?

編輯:

此外,假定b.h包括另一頭文件包括stdbool.h - 即使b.h具有stdbool.h既從該類和a.h。會導致錯誤嗎?

回答

1

所有的C標準頭必須作出這樣它們可以被包含多次,在任何順序:

Standard headers may be included in any order; each may be included more than once in a given scope, with no effect different from being included only once

1

如果stdbool.h本身包含警衛(#ifndef),那麼一切都會好起來的。否則,你可能最終會包含一些標題兩次。會造成問題嗎?這取決於。如果包含兩次的頭只包含聲明,那麼一切都會編譯 - 只需要幾個納秒的時間。想象一下:

int the_answer(void); // <-- from first inclusion 
int the_answer(void); // <-- from from second inclusion - this is OK 
         //  at least as long as declarations are the same 

int main() 
{ 
    return the_answer(); 
} 

如果在另一方面就會有定義,它會導致一個錯誤:

int the_answer(void) // <-- from first inclusion - OK so far 
{ 
    return 42; 
} 

int the_answer(void) // <-- from second inclusion 
{      //  error: redefinition of 'the_answer' 
    return 42; 
} 

int main() 
{ 
    return the_answer(); 
} 
+1

定義的完整標題一旦你從多個文件中使用相同的頭文件,無論如何都會導致鏈接錯誤,所以不要這樣做。 – 2012-03-13 19:16:46

0

這是正常現象,大多數頭開始

#ifndef _HEADERFILENAME_H_ 
#define _HEADERFILENAME_H_ 

和結尾使用以下行:

#endif 

如果包括頭兩次,第二次你PROGRAMM不會再有因爲#ifndef#define#endif