6

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?

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    A related question pertaining to C++: http://stackoverflow.com/questions/12125014/are-there-limits-to-how-deep-nesting-of-header-inclusion-can-go . One of the answers gives a quote from the C++ standard as recommending, but not necessarily requiring, support for at least 256 nested includes. Many implementations support much deeper nesting. – Jim Lewis May 18 '17 at 20:05

1 Answers1

4

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • I was wondering what effect would `#pragma once` have on preventing looping? – ryyker May 18 '17 at 20:14
  • @ryyker Yes it will. Same as include guards (`#ifndef X #define X #endif`), as long as you put includes inside them, which you should be doing. – J_S May 18 '17 at 21:01