for example, want 2 header files can depend on function other header file.
//header1.h file #include header2.h void h1(){ //... func1(); } void h2(); //header2.h file #include header1.h void func1(); void func2(){ //some other code... h2(); } this may not seem big of issue, in order files logically coherent, want kind of dependency. i've ran issue multiple times in visual studio, while compiling c++ code. never compiles when include respective header guards each file, i.e.
#ifndef header1_h #define header1_h //header1.h... #endif why isn't allowed? or, there way compile work?
firstly, #include preprocessor directive performs full textual substitution of 1 text file text file. 2 header files trying #include each other form infinite loop of nested textual substitutions. think should obvious infinite loop of textual substitutions not "work", because infinite.
secondly, using #ifndef include guards in header file break infinite loop @ point. i.e. circular inclusion turn sequential inclusion 1 file included first , file included second. sequential inclusion (in order) not resolve circular declaration dependencies present in header files.
for reason circular inclusion of header files never makes sense (aside form special contexts, preprocessor tricks), regardless of whether use include guards or not. circular inclusion never achieves anything. have design header files don't attempt rely on circular inclusion. i.e. have stratify declarations , header files lower-level , higher-level ones, , include lower higher (but not other way around), , resolve circular declaration dependencies using forward-declarations in lower-level headers.
sometimes header files call circular inclusion because poorly designed. example, when there no circular dependencies between declarations, these declarations might incorrectly distributed between header files, leading perceived need include headers each other circularly. in such cases better idea refactor headers in order eliminate circular declaration dependencies. e.g. redistribute declarations between headers, extract portions of 2 mutually dependent headers third lower-level header etc. , when such refactoring not possible, i.e. have genuine circular declaration dependency, use forward-declarations last resort.
Comments
Post a Comment