Skip to content

Instantly share code, notes, and snippets.

@lyxal

lyxal/eh.md Secret

Created July 28, 2021 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lyxal/c1e8bfb1e0276b34d0c36b4c46c8d8e2 to your computer and use it in GitHub Desktop.
Save lyxal/c1e8bfb1e0276b34d0c36b4c46c8d8e2 to your computer and use it in GitHub Desktop.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment