C Programming - C Preprocessor - Discussion


There exists a way to prevent the same file from getting #included twice in the same program.

[A]. True
[B]. False

Answer: Option A


True, We can prevent the same file from getting included again by using a preprocessor directive called #ifndef (short for "if not defined") to determine whether we've already defined a preprocessor symbol called XSTRING_H. If we have already defined this symbol, the compiler will ignore the rest of the file until it sees a #endif (which in this case is at the end of the file).

#ifndef XSTRING_H

#define XSTRING_H defines the same preprocessor symbol,

Finally, the last line of the file, #endif

Archana said: (Sep 23, 2011)  
Can anyone explain in detail.

P@1 said: (Aug 20, 2012)  
Can't understand please explain in detail.

Bunty said: (Nov 2, 2012)  
#ifndef is a preprocessor directive which means if not defined
For example you made your own file file1.h with a func f1()
Included it in another file file2.h

Now finally in your program
If u include
Include file1.h and file2.h
It will give error
For multiple declaration for function f1()

To avoid this declare the function like this in file1.h

#ifndef FUNF1
#define FUNF1
f1() {/*some code*/}

So what will happen now
For the first time compiler with go through include file1.h
FUNF1 is not present it will be define and f1()subsequently
Now,when file2.h get included it already has file1 include but this time
As FUNF1 is already defined compiler doesn't go beyond that.

Macik said: (Nov 9, 2015)  
Maybe the answer is not 100% correct. There is no mechanism in C to prevent #including. #include will always include whole file. The mechanism is included in the file itself.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.