Programming in C

(Barry) #1

314 Chapter 13 The Preprocessor


Suppose you are writing a series of programs for performing various metric conver-
sions.You might want to set up some defines for all of the constants that you need to
perform your conversions:
#define INCHES_PER_CENTIMETER 0.394
#define CENTIMETERS_PER_INCH 1 / INCHES_PER_CENTIMETER

#define QUARTS_PER_LITER 1.057
#define LITERS_PER_QUART 1 / QUARTS_PER_LITER

#define OUNCES_PER_GRAM 0.035
#define GRAMS_PER_OUNCE 1 / OUNCES_PER_GRAM
...
Suppose you entered the previous definitions into a separate file on the system called
metric.h.Any program that subsequently needed to use any of the definitions contained
in the metric.hfile could then do so by simply issuing the preprocessor directive
#include "metric.h"
This statement must appear before any of the defines contained in metric.hare refer-
enced and is typically placed at the beginning of the source file.The preprocessor looks
for the specified file on the system and effectively copies the contents of the file into the
program at the precise point that the #includestatement appears. So, any statements
inside the file are treated just as if they had been directly typed into the program at that
point.
The double quotation marks around the include filename instruct the preprocessor to
look for the specified file in one or more file directories (typically first in the same
directory that contains the source file, but the actual places the preprocessor searches are
system dependent). If the file isn’t located, the preprocessor automatically searches other
systemdirectories as described next.
Enclosing the filename within the characters <and >instead, as in
#include <stdio.h>
causes the preprocessor to look for the include file in the special system include file
directory or directories. Once again, these directories are system dependent. On Unix
systems (including Mac OS X systems), the system include file directory is
/usr/include, so the standard header file stdio.hcan be found in
/usr/include/stdio.h.
To see how include files are used in an actual program example, type the six defines
given previously into a file called metric.h.Then type in and run Program 13.3.

Program 13.3 Using the #includeStatement
/* Program to illustrate the use of the #include statement
Note: This program assumes that definitions are
set up in a file called metric.h */
Free download pdf