Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C language: recursive #include

I came across such piece of code:

a.h:

#include "b.h"
/* structure definitions, macros etc. */

b.h:

    #include "a.h"
/* structure definitions, macros etc. */

Is this legal from the C standard point of view? I would think such approach isn't safe.

like image 978
Mark Avatar asked Dec 02 '25 10:12

Mark


2 Answers

You need to use include guards. Then it will be safe.

a.h
#ifndef A_H
#define A_H
/* ... */

#endif
like image 167
cnicutar Avatar answered Dec 05 '25 00:12

cnicutar


It is legal. All compilers that I know of impose a nesting limit, usually in the range of 20 to 50. Recursion, if useful, is easily controlled with condtionals:

#if NESTING < 5
 #define NESTING NESTING+1
 #include "myself.h"
#endif

There are thousands of ways to shoot yourself in the foot as a programmer. This is just one more way. Be careful.

like image 34
wallyk Avatar answered Dec 04 '25 23:12

wallyk