2017-05-18 9 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答えの1つは、少なくとも256個のネストされたインクルードのサポートを推奨していますが、必須ではありません。多くの実装では、より深いネストがサポートされています。 –

答えて

4

コンパイラによって異なる制限があります。

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

だから標準状態準拠実装は、少なくともサポートしなければならない[C標準])(http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf)のセクション6.10.2から

15レベルの深さですが、それ以上の可能性があります。

実際には、インクルードファイルにループが発生しない限り、おそらくこのような制限はありません。

たとえば、あなたがこれを行う場合:

main.h:

#include "main.h" 

extern int x; 

のmain.c:

error: #include nested too deeply

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

int x = 2; 

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

gccはあなたに次のエラーを与えます

私の場合(gcc 4.8.5)それはエラーが出る前に約200レベル深くなった。詳細は、the gcc preprocessor manual, section 11.2を参照してください。

MSVCの場合、インクルードの深さは10(see here)です。これは、MSVCが標準準拠のコンパイラではないことを(他の理由の中でも)意味することに注意してください。

+0

'#pragma once'はループを防ぐのにどんな効果があるのだろうか? – ryyker

+0

@ryykerはいそうです。includeガード( '#ifndef X #define X#endif')と同じですが、内部にインクルードする必要があります。 –

関連する問題