Click here to Skip to main content
15,887,434 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
in my project, in almost every header file, ther is a corresponding line in the top,like
in file a.h
#ifndef A_H
#def A_H
similarly in other files also.
what is its use?
Posted

1 solution

To ensure the header file is only included once. Otherwise the linker will detect a duplicate definition for functions,data structures, etc.

Some compilers support #pragma once, which does the same thing. However, this is non-standard.
 
Share this answer
 
Comments
harshanettar 2-May-11 13:42pm    
thanks. can u explain me in detail.?
in my code, only
#ifndef A_H
#def A_H
exists. i searched in the entire project for reference of this definition(A_H).then,where it is used?
Richard MacCutchan 2-May-11 14:03pm    
It is only defined and used in the above lines that you can see. This ensures that if this header is included more than once anywhere in the project, then the actual definitions inside it will still only be included once.
NuttingCDEF 2-May-11 14:07pm    
The lines you've quoted are the ONLY place it is likely to be used.

Whenever the compiler includes your a.h file, the first thing it does is check whether A_H is defined (ifndef) - if it isn't the compiler knows a.h has not yet been included in that compilation unit and processes the rest of the file (including defining A_H) - alternatively, if A_H is already defined, the compiler knows that a.h has already been processed so won't process it again - note that the #ifndef will have a corresponding #endif at the end of the file

Other files b.h, c.h etc. (or whatever) will have similar constructs using B_H, C_H etc. to make sure they only get processed once.

This matters because if you have a declaration like:

void myfunc(int myarg);

if the compiler processes it twice it will generate an error because it has seen a duplicate declaration.

It's easy to spot errors where a.h is included twice in the same source file - but if x.c #includes a.h and b.h and b.h also #includes a.h, problems with the double inclusion of a.h can be hard to spot. Using the #ifndef A_H etc., it doesn't matter.
harshanettar 2-May-11 14:13pm    
thanks very much for detailed explanation. one more doubt on your explanation. what is the problem of double inclusion of header files? ie. if there is any procbem or it is just optimisation?
Rick Shaub 2-May-11 14:18pm    
If you include the header elsewhere, the linking process will fail in due to a previously defined variable, function etc.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900