In C++, what is the purpose of include guards in a header?
I have read that it is for preventing including files again and again, but how do header guard guarantee this
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The guard header (or more conventionally "include guard") is to prevent problems if header file is included more than once; e.g.
The first time this file is
#include-ed, theMARKERpreprocessor symbol will be undefined, so the preprocessor will define the symbol, and the following declarations will included in the source code seen by the compiler. On subsequent#include‘s, theMARKERsymbol will be defined, and hence everything within the#ifndef/#endifwill be removed by the preprocessor.For this to work properly, the
MARKERsymbol needs to be different for each header file that might possibly be#include-ed.The reason this kind of thing is necessary is that it is illegal in C / C++ to define a type or function with the same name more than once in a compilation unit. The guard allows you to
#includea header file without worrying if has already been included. Without the guard, multiple inclusions of the same header file would lead to unwanted redeclarations and compilation errors. This is particularly helpful when header files need to#includeother header files.In short, it doesn’t prevent you from
#include-ing a file again and again. Rather, it allows you to do this without causing compilation errors.