标头包含深度限制 [英] Header Inclusion Depth Limit

查看:53
本文介绍了标头包含深度限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,当包含头文件时,包含文件的深度可以无限增加吗?您可以在编译时指定一个限制吗?

示例:

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) 

我正确吗?头文件可以无限添加吗?

解决方案

根据编译器的不同,存在一个限制.

摘自[C标准] 6.10.2节)(

main.c:

  #include< stdio.h>#include"main.h"int x = 2;int main(){printf("x =%d \ n",x);返回0;} 

gcc会给您以下错误:

错误:#include嵌套太深

在我的情况下(gcc 4.8.5),它在出错之前已经深入了200多个级别.有关详细信息,请参见 gcc预处理程序手册,第11.2节./p>

对于MSVC,它支持10的包含深度(请参见此处).请注意,这(除其他原因外)还意味着MSVC不是符合标准的编译器.

I was wondering, when including header files, can the depth of include files increase without limit? Can you specify a limit at compile time?

Example:

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 )

Am I correct? Can header files be included endlessly?

解决方案

There is a limit which differs based on the compiler.

From section 6.10.2 of the [C standard])(http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf):

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).

Section 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

So the standard states that conforming implementations must support at least 15 levels deep, but possibly more.

In practice, you probably won't hit such a limit unless you end up with a loop in your include files.

For example if you do this:

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 will give you the following error:

error: #include nested too deeply

In my case (gcc 4.8.5), it went about 200 levels deep before it errored out. See the gcc preprocessor manual, section 11.2 for details.

For MSVC, it supports an include depth of 10 (see here). Note that this means (among other reasons) that MSVC is not a standard-conforming compiler.

这篇关于标头包含深度限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆