Avoiding Multiple Inclusion of Header Files

#ifndef

  • Often several program files use the same header file containing typedef statements, constants, or class type declarations
  • But, it is a compile-time error to define the same identifier twice within the same namespace
  • The preprocessor directive #ifndef is used to avoid the compilation error that would otherwise occur from multiple uses of #include for the same header file.
  • Syntax:

#ifndef Preprocessor_Identifier
#define Preprocessor_Identifier

 . . . /* Header File Code */

#endif

Example For example, consider the class files Time.h and Time.cpp, and a client that uses it client.cpp. For compilation the class declaration in file time.h will be included only once.


// time .h 		 
// Specification file 	   	 					
#ifndef   TIME_H 
#define  TIME_H	 	          

class Time
 public:
       .  .  . 	        /* Public methods */	
        	      
 private: 					
       .  .  .	        /* Private data and functions */			
};
#endif

// time .cpp 
// IMPLEMENTATION FILE
#include time.h
...


// client.cpp
// Appointment program
 #include time.h
int   main (void)
{
  ...
}

Alternate method

The following method will also work to prevent multiply defined header files:

#pragma once

/* header file code */

All code after the #pragma once will only be included once.


-- JimSkon - 2011-03-11

Topic revision: r2 - 2011-04-22 - JimSkon
 
This site is powered by the TWiki collaboration platformCopyright &© by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback