Monday 14 January 2013

What Are Macro Guards ?


What are Macro Guards  ?

Macro Guards are basically constructs to eliminate any chances of  inclusion of any header file more that once. Delving more into the technical aspect, we see that they are  actually pre-processor directive(s) included in header file(s). Let's have a look at it.
   
Example : Consider  header file <area.h>

                                                                  area.h
#ifndef __area_h__  //Macro guards
#define __area_h__ 

//Contents of header file
// Structure is defined here in the header file

struct area
{
float length;
float width ;
}
#endif


In above example :
  • __area_h__ is name of macro it can be any name but make sure that it is unique for each header file. 
  • #ifndef - Preprocessor Directive which means if not defined . If in object file generated by compiler above macro __area_h__ is already defined then rest of header file won't be executed else whole header file will be executed
  • #define - To define variable
  • #endif - To end if block
 for example shown, #ifndef are called as Marco Guards. They guard the whole header file and eliminate chances of their inclusion more that once.

Let's see how ??
Consider one example shown below :


Here class AREA_RECTANGLE is inherited from AREA_SQUARE class.

Implementation of area_rectangle class

                                                          area_rectangle.cpp
#include"area.h"

class area_rectangle
{
  //Implementation of class goes here
};



                                                       area_square.cpp
#include"area.h"

class area_square::public area_rectangle
{
  //Implementation of class goes here
};



Now  in both classes i.e. area_rectangle and area_square, area.h is included .So if we compile area_square.cpp that would add structure  area twice
  1.  one from header file included in area_square.cpp and other from 
  2. area_rectangle.cpp (as area_square class inherits area_rectangle). 
This will throw error saying that member "length" and "width" are already defined.





But due to Macro Guards once __area_h__ is defined in object file while compiling area_rectangle.cpp so again area.h won't be included even if it is included in area_square.cpp
and program is completed successfully.


No comments:

Post a Comment