我想知道,当包含头文件时,包含文件的深度可以无限制地增加吗?你能在编译时指定一个限制吗?
例:
main.c中:
#include "A.h"
const int xyz = CONST_VALUE;
Run Code Online (Sandbox Code Playgroud)
啊:
#include "B.h"
Run Code Online (Sandbox Code Playgroud)
BH:
#include "C.h"
Run Code Online (Sandbox Code Playgroud)
...
...
...
ZH:
#define CONST_VALUE ( 12345 )
Run Code Online (Sandbox Code Playgroud)
我对么?可以无限地包含头文件吗?
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
#includepreprocessing 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;
Run Code Online (Sandbox Code Playgroud)
main.c:
#include <stdio.h>
#include "main.h"
int x = 2;
int main()
{
printf("x=%d\n",x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
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.