Are there limits to how deep nesting of header inc

2020-04-05 08:33发布

问题:

I can't find anything on MSDN or elsewhere, but are there hard-coded limits to how deep nesting of header inclusion can go? Example:

// H1.h
// guards etc.
#include "H2.h"

// H2.h
// guards etc.
#include "H3.h"

//...

// HN.h <---- how large can N get??

I wonder if there is anything in the Standard about this. If the answer is implementation defined, then I'm primarily interested in the Visual Studio toolchain.

回答1:

The standard also says something about it (in the part about implementation quantities, annex B):

The limits may constrain quantities that include those described below or others. The bracketed number following each quantity is recommended as the minimum for that quantity. However, these quantities are only guidelines and do not determine compliance.

...

  • Nesting levels for #include files [256].

Note that this is only a recommended minimum, so a compiler may not support that many inclusions (but most compilers do, as shown in other answers).



回答2:

I wrote a header file that includes itself and compiled it with MSVS 2010. That gave the error message:

fatal error C1014: too many include files : depth = 1024


回答3:

Yes: 200. At least for my version of gcc.

It can be easily tested:

#!/bin/bash

i=0

touch "test$i.c"

while gcc -c "test$i.c"; do
  j="$[ $i + 1 ]"
  echo "#include \"test$i.c\"" > "test$j.c"
  i="$j"
  echo "$j" | grep -q "000$" && echo "$j are fine"
done

This yields:

In file included from test2.c:1:0,
             from test3.c:1,
             from test4.c:1,
             ...
             from test198.c:1,
             from test199.c:1,
             from test200.c:1:
test1.c:1:19: error: #include nested too deeply


回答4:

From MSDN for Visual Studio 2012:

Nesting of include files can continue up to 10 levels.

UPDATE:

This "official" limit is probably more of a guideline so that people won't start to stack include files for no reason. I do not believe that there has been a compiler with so restrictive inclusion limits for a couple of decades at least.

For example, according to one of the other answers at least one version of the VS C++ compiler supports about 1024 nesting levels.