How are circular #includes resolved?

后端 未结 4 1753
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 12:06

In c lets say we have 2 files

1.h

#include<2.h>

blah blah

and we have 2.h

#include<1.h>

code
         


        
4条回答
  •  天命终不由人
    2020-11-29 12:29

    Circular inclusions must be eliminated, not "resolved" with include guards (as the accepted answer suggests). Consider this:

    1.h:

    #ifndef HEADER_1_h
    #define HEADER_1_h
    #include "2.h"
    
    #define A 1
    #define B 2
    
    #endif // HEADER_1_h
    

    2.h:

    #ifndef HEADER_2_h
    #define HEADER_2_h
    #include "1.h"
    
    #if (A == B)
    #error Impossible
    #endif
    
    #endif // HEADER_2_h
    

    main.c:

    #include "1.h"
    

    This will throw the "Impossible" error at compile time, because "2.h" fails to include "1.h" due to include guards, and both A and B become 0. In practice, this leads to hard to track errors which appear and disappear depending on the order in which header files are included.

    The right solution here would be to move A and B to "common.h" which then could be included in both "1.h" and "2.h".

提交回复
热议问题