Programming in C

(Barry) #1
Conditional Compilation 317

If you had a large program that had many such dependencies on the particular hard-
ware and/or software of the computer system (and this should be minimized as much as
possible), you might end up with many defines whose values would have to be changed
when the program was moved to another computer system.
You can help reduce the problem of having to change these defines when the pro-
gram is moved and can incorporate the values of these defines for each different
machine into the program by using the conditional compilation capabilities of the pre-
processor. As a simple example, the statements


#ifdef UNIX


define DATADIR "/uxn1/data"


#else


define DATADIR "\usr\data"


#endif


have the effect of defining DATADIRto "/uxn1/data"if the symbol UNIXhas been previ-
ously defined and to "\usr\data"otherwise. As you can see here, you are allowed to
put one or more spaces after the #that begins a preprocessor statement.
The #ifdef,#else,and #endifstatements behave as you would expect. If the sym-
bol specified on the #ifdefline has been already defined—through a #definestatement
or through the command line when the program is compiled—then lines that follow up
to a #else,#elif, or #endifare processed by the compiler; otherwise, they are ignored.
To define the symbol UNIXto the preprocessor, the statement


#define UNIX 1


or even just


#define UNIX


suffices. Most compilers also permit you to define a name to the preprocessor when the
program is compiled by using a special option to the compiler command.The gcccom-
mand line


gcc -D UNIX program.c


defines the name UNIXto the preprocessor, causing all #ifdef UNIXstatements inside
program.cto evaluate as TRUE (note that the -D UNIXmust be typed beforethe pro-
gram name on the command line).This technique enables names to be defined without
having to edit the source program.
A value can also be assigned to the defined name on the command line. For example,


gcc -D GNUDIR=/c/gnustep program.c


invokes the gcccompiler, defining the name GNUDIRto be the text /c/gnustep.


Avoiding Multiple Inclusion of Header Files


The #ifndefstatement follows along the same lines as the #ifdef.This statement is
used the same way the #ifdefstatement is used, except that it causes the subsequent
lines to be processed if the indicated symbol is notdefined.This statement is often used
to avoid multiple inclusion of a file in a program. For example, inside a header file, if you

Free download pdf