Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why include guards?

Include guards, as defined here, are used to prevent loading the same code twice at compilation.

Why can't my compiler (GCC) detect that it is loading the same code twice and have a sensible default behaviour?

like image 292
ximus Avatar asked Jan 13 '14 11:01

ximus


People also ask

Why are include guards important?

Include guards ensures that compiler will process this file only once, no matter how many times it is included. Include guards are just series of preprocessor directives that guarantees file will only be included once.

Is include guard necessary?

Formally, you don't need include guards in your bar. h . It has a single function declaration, which can be repeated many times in one translation units. So, including this header multiple times will not lead to errors.

Why should we use include guards in our header files?

Header guards are designed to ensure that the contents of a given header file are not copied, more than once, into any single file to prevent duplicate definitions. This is a good thing because we often need to reference the contents of a given header from different project files.

What problem can occur when a C++ header file lacks include guards?

These user-defined types are typically defined in header files, so the type definitions can be propagated out to the code files that need to use them. Without a header guard, a code file could end up with multiple (identical) copies of a given type definition, which the compiler will flag as an error.


1 Answers

Simply because you might have wanted the compiler to load that file twice.

Remember, that #include simply loads a file and puts its contents in the place of the directive. This file might be a header file, but may be useful and frequently used piece of source code as well.

Most modern compilers react to #pragma once doing exactly what you want them to. Remember though, that this is a compiler extension not included in the language specification and it is generally a good idea to stick to include guards - you'll be certain, that it works on every compiler and in any circumstances.

like image 128
Spook Avatar answered Sep 20 '22 00:09

Spook