340 Chapter 15 Working with Larger Programs
Figure 15.1 Communication between modules.
mod1.cdefines two global variables:xand result,both of type double.xcan be
accessed by any module that is linked together with mod1.c. On the other hand, the
keyword staticin front of the definition of resultmeans that it can only be accessed
by functions defined inside mod1.c(namely mainand doSquare).
When execution begins, the mainroutine calls doSquare.This function assigns the
value 2.0to the global variable xand then calls the function square. Because squareis
defined in another source file (inside mod2.c), and because it doesn’t return an int,
doSquareproperly includes an appropriate declaration at the beginning of the function.
The squarefunction returns as its value the square of the value of the global variable
x. Because squarewants to access the value of this variable, which is defined in another
source file (in mod1.c), an appropriate externdeclaration appears in mod2.c(and, in this
case, it makes no difference whether the declaration occurs inside or outside the square
function).
The value that is returned by squareis assigned to the global variable resultinside
doSquare, which then returns back to main.Inside main, the value of the global variable
resultis displayed.This example, when run, produces a result of 4.0 at the terminal
(because that’s obviously the square of 2.0).
Study the example until you feel comfortable with it.This small—albeit impractical—
example illustrates very important concepts about communicating between modules, and
it’s necessary that you understand these concepts to work effectively with larger
programs.
double x;
static double result;
static void doSquare (void)
{
double square (void);
x = 2.0;
result = square ();
}
int main (void)
{
doSquare ();
printf ("%g\n", result);
return 0;
}
extern double x;
double square(void)
{
return x * x;
}
mod1.c mod2.c