2017-05-18 95 views
6

我想知道,包含頭文件時,包含文件的深度能夠不受限制地增加嗎?你可以在編譯時指定一個限制嗎?頭文件包含深度限制

實施例:

main.c中:

#include "A.h" 
const int xyz = CONST_VALUE; 

A.H:

#include "B.h" 

B.h:

#include "C.h" 

...

...

...

Z.h:

#define CONST_VALUE (12345) 

,對嗎?可以將頭文件無限包含在內?

+1

有關C++的相關問題:http://stackoverflow.com/questions/12125014/are-there-limits-to-how-deep-nesting-of-header-inclusion-can-go。其中一個答案給出了C++標準的引用,作爲推薦,但不一定要求,支持至少256個嵌套包含。許多實現支持更深的嵌套。 –

回答

4

根據編譯器的不同有一個限制。

從[C標準])(http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf)第6.10.2:

6 A #include preprocessing directive may appear in a source file that has been read because of a #include directive in another file, up to an implementation-defined nesting limit (see 5.2.4.1).

節5.2.4.1:

The implementation shall be able to translate and execute at least one program that contains at least one instance of every one of the following limits:

...

  • 15 nesting levels for #included files

所以標準規定符合實現必須至少支持15層深,但可能更多。

實際上,除非最終在包含文件中出現循環,否則可能不會達到此限制。

例如,如果你這樣做:

main.h:

#include "main.h" 

extern int x; 

的main.c:

#include <stdio.h> 
#include "main.h" 

int x = 2; 

int main() 
{ 
    printf("x=%d\n",x); 
    return 0; 
} 

GCC會給你以下錯誤:

error: #include nested too deeply

在我的情況(gcc 4.8.5) ,它在出現錯誤之前深入了大約200個關卡。有關詳細信息,請參閱the gcc preprocessor manual, section 11.2

對於MSVC,它支持包含深度爲10(see here)。請注意,這意味着(除其他原因)MSVC不符合標準的編譯器。

+0

我想知道'#pragma once'對防止循環有什麼影響? – ryyker

+0

@ryyker是的。和包含守衛('#ifndef X #define X#endif')一樣,只要你把包含在裏面,你應該這樣做。 –