question archive C++ Which directive is used to create an “include guard”, which allows a program to be conditionally compiled
Subject:Computer SciencePrice:2.87 Bought7
C++
Which directive is used to create an “include guard”, which allows a program to be conditionally compiled. This prevents a header file from being included more than once.
#include |
||
#guard |
||
#ifndef |
||
endif |
Answer:
We correct directive is #ifndef to prevents a header file from being included more than once.
It has the following syntax
#ifndef <testmacro> /* code section 1 */ #else /* code section 2 */ #endif So it simply checks whether testmacro is defined or not.If it is defined then it executes code section 1 otherwise code section 2. So how can we use it?
Parent.h
#ifndef PARENT_H #define PARENT_H /*Code of header File*/
#endif
So suppose somebody tries to include this file twice, so in the first inclusion as PARENT_H is not defined so file will be included with all the code between #define PARENT_H and #endif and PARENT_H will get defined by #define PARENT_H statement. Now if we are including this file again then we will get PARENT_H as already defined so the compiler will skip all the code inside the code between #define PARENT_H and #endif. So the file will be included only once.