IntheCandC++programminglanguages,an#includeguard,sometimescalledamacroguard,headerguardorfileguard,isaparticularconstructusedtoavoidtheproblemofdoubleinclusionwhendealingwiththeincludedirective.TheCpreprocessorprocessesdirectivesoftheform#includeinasourcefilebylocatingtheassociatedfileondiskandtranscluding("including")itscontentsintoacopyofthesourcefileknownasthetranslationunit,replacingtheincludedirectiveintheprocess.Thefilesincludedinthisregardaregenerallyheaderfiles,whichtypicallycontaindeclarationsoffunctionsandclassesorstructs.IfcertainCorC++languageconstructsaredefinedtwice,theresultingtranslationunitisinvalid.#includeguardspreventthiserroneousconstructfromarisingbythedoubleinclusionmechanism.Theadditionof#includeguardstoaheaderfileisonewaytomakethatfileidempotent.Anotherconstructtocombatdoubleinclusionis#pragmaonce,whichisnon-standardbutnearlyuniversallysupportedamongCandC++compilers.
#includeguardsareusedtoavoidaccidentallyincludingsomefileindirectlythroughtheuseofconstantsthataredefinedinanotherfile.Theincludedirectiveisinterpretedasacommandtotransclude(include)thefilewiththeincludedirectiveintothecurrentfilewheneveritisencountered.Thefollowingexampleillustratestheproblemwiththisapproachwhenconstantsthataredefinedinonedirectiveareusedinanother.
#include #include using namespace std; int main (void) { const double pi = 4; double area = pi * radius * radius; cout << "The area of a circle of radius " << radius << " is " << area << "." << endl; return 0; }
Thevariableareaisthenusedtodeterminetheareaofacirclewithar