Embedded Basics – Header Guards

Header guards are an important feature that should be included in ALL header files.  The purpose of a header guard is to prevent macros, typedefs, enums and function prototypes from accidentally being included in a source file twice.  If these definitions do get included twice it can lead to a compiler error due to a double definition. The use of a header guard will easily solve this problem.  A header guard consists of three parts.

1) Checking whether a macro related to this file has been previously defined through the use of #ifndef

2) If the macro hasn’t been previously defined then the macro is now defined using #define

3) Closing of the #ifndef block using #endif

Below is an example of how a header guard might look for a file named button.


In the event that a header is included twice, the preprocessor check will see that the macro associated with the header has already been defined and will not once again include the header file.  A common practice is to define a macro that is the name of the file with an underscore being used to separate any white space and the file extension.

Share >

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.