The #if !defined(HDR) trick is a bit esoteric to start out with. Let's look at a simpler example: in ANSI C, the remove function deletes a file. On some older Unix systems, however, the function to delete a file is instead named unlink. Therefore, when deleting a file, we might use code like this:
#if defined(unix) unlink(filename); #else remove(filename); #endifWe would arrange to have the macro unix defined when we were compiling our program on a Unix machine, and not otherwise.
You may wonder what the difference is between the if() statement we've been using all along, and this new #if preprocessing directive. if() acts at run time; it selects whether or not a statement or group of statements is executed, based on a run-time condition. #if, on the other hand, acts at compile time; it determines whether certain parts of your program are even seen by the compiler or not. If for some reason you want to have two slightly different versions of your program, you can use #if to separate the different parts, leaving the bulk of the code common, such that you don't have to maintain two totally separate versions.
#if can be used to conditionally compile anything: not just statements and expressions, but also declarations and entire functions.
Back to the HDR example (though this is somewhat of a tangent, and it's not vital for you to follow it): it's possible for the same header file to be #included twice during one compilation, either because the same #include line appears twice within the same source file, or because a source file contains something like
#include "a.h" #include "b.h"but b.h also #includes a.h. Since some declarations which you might put in header files would cause errors if they were acted on twice, the #if !defined(HDR) trick arranges that the contents of a header file are only processed once.
Note that two different macros, both named HDR, are being used on page 91, for two entirely different purposes. At the top of the page, HDR is a simple on-off switch; it is #defined (with no replacement text) when hdr.h is #included for the first time, and any subsequent #inclusion merely tests whether HDR is #defined. (Note that it is in fact quite possible to define a macro with no replacement text; a macro so defined is distinguishable from a macro which has not been #defined at all. One common use of a macro with no replacement text is precisely as a simple #if switch like this.)
At the bottom of the page, HDR ends up containing the name of a header file to be #included; the name depends on the #if and #elif directives. The line
#include HDR#includes one of them, depending on the final value of HDR.
Read sequentially: prev next up top
This page by Steve Summit // Copyright 1995, 1996 // mail feedback