How multiple inclusion of same function is avoided in C Language - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

How multiple inclusion of same function is avoided in C Language

Share This

As programs grow, or as you use header files more often, you run the risk of accidentally including a header file more than once. This can make confusion for the compiler, as the compiler gets more than one definition of the same function. This can be avoided by using preprocessor directives. Look at the example shown below.


/* PROG.H - A header file with a check to prevent multiple includes! */ #if defined( PROG_H ) /* the file has been included already */ #else #define PROG_H /* Header file information goes here... */ #endif
Let us examine, what this header file does. First, it is checked whether PROG_H is defined. 
 
Note that PROG_H is similar to the name of the header file. If PROG_H is not defined, it is to be defined. 
 
How does PROG_H get defined? 
 
When first time this header is included, the preprocessor checks whether PROG_H is defined. It won't be, so control goes to the #else statement. The first thing done after the #else is to define PROG_H so that any other inclusions of this file skip the body of the file. Lines 7 through 11 can contain any number of commands or declarations.



Happy Exploring!

No comments:

Post a Comment