Checking the header file multiple inclusion or re-definition C++ program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info:

To do: Checking the multiple inclusion or re-definition of the header file using #ifndef, #define and #endif in C++ programming

To show: How to use the C/C++ preprocessor directives, #ifndef, #define and #endif to check the header files multiple inclusion or re-definition of the header file in C++ programming

 

Create a user defined header file named boolean.h: Create an empty Win32 console mode application project. Then add the header file: Projects -> Add New Item... -> Visual C++ -> Code -> Header File (.h) ->put the named as boolean -> Click the Add button -> copy and paste the following code:

 

// avoiding the boolean.h header file from multiple inclusion or re-definition

#ifndef BOOLEAN_H

// means literal string 'int' is same as 'boolean'

typedef int boolean;

const boolean FALSE = 0;

const boolean TRUE =1;

#define BOOLEAN_H

#endif

 

 

Add a new C++ source file and then run the following main() program

 

 

// program example using the user defined header file, boolean.h

#include <iostream>

#include <cstdlib>

// notice this

#include "boolean.h"

using namespace std;

 

int main(void)

{

// new type stored in boolean.h

boolean HappyTime;

HappyTime = TRUE;

// if TRUE = 1, do

if(HappyTime)

cout<<"I'm happy today lor!!!"<<endl;

// else, FALSE = 0, do...

else

cout<<"What a bad day...today!!!"<<endl;

return 0;

}

 

Output example:

 

I'm happy today lor!!!

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index