Tuesday, 14 April 2015

Use of include guard in c or c++

USE OF INCLUDE GUARD

Header files are often of the form
 
    #ifndef FOO
     #define FOO
     ...
     #endif

to prevent the compiler from processing them more than once. The preprocessor notices such header files, so that if the header file appears in a subsequent #include directive and FOO is defined, then it is ignored and it doesn't preprocess or even re-open the file a second time. This is referred to as the multiple include optimization.

For example,
 lets say you have two header files, a.h and b.h. The header file b.h includes a.h, and then both a.h and b.h is included in the source file s.c. Without header guards the file a.h will be included twice, which can cause errors. If the header files had header guards then the file a.h would only be included once.
You don't need header guards in source files because usually you don't include them in other files.

In CeePlusPlus you can guard against a header file being included more than once with what is called an IncludeGuard.
A naive compiler will reload the file every time it's included. To avoid that, put RedundantIncludeGuards around the include:

header.h
  #ifndef HEADER_H_
  #define HEADER_H_
  // declarations
  #endif

foo.c
  #ifndef HEADER_H_
  #include "header.h"
  #endif

If the preprocessor sees this sequence after once including header.h (and therefore defining HEADER_H_) it will skip over the #include directive entirely - without scanning, or even opening, header.h.
This example is slightly misleading. Note:

Using Redundant Include Guards in implementation files has much less gain than doing the same in a header, and adds quite a bit more confusion due to the usually larger number of includes there.
In other words:

header.h
  #ifndef HEADER_H_
  #define HEADER_H_
  // declarations
  #endif

fooheader.h
  #ifndef HEADER_H_
  #include "header.h"
  #endif