Programming in C

(Barry) #1
Communication Between Modules 337

variable moveNumbernot just as a global variable, but also as an externalglobal variable.To
reference the value of an external global variable from another module, you must declare
the variable to be accessed, preceding the declaration with the keyword extern,as
follows:


extern int moveNumber;


The value ofmoveNumbercan now be accessed and modified by the module in which
the preceding declaration appears. Other modules can also access the value of
moveNumberby incorporating a similar externdeclaration in the file.
You must obey an important rule when working with external variables.The variable
has to be definedin some place among your source files.This is done in one of two ways.
The first way is to declare the variable outside of any function,notpreceded by the key-
word extern, as follows:


int moveNumber;


Here, an initial value can be optionally assigned to the variable, as was shown previously.
The second way to define an external variable is to declare the variable outside of any
function, placing the keyword externin front of the declaration, and explicitly assigning
an initial value to it, as follows:


extern int moveNumber = 0;


Note that these two ways are mutually exclusive.
When dealing with external variables, the keyword externcan only be omitted in
one spot throughout your source files. If you don’t omit the keyword in any one spot, in
exactly one place, you must assign the variable an initial value.
Ta ke a look at a small program example to illustrate the use of external variables.
Suppose you type the following code into a file called main.c:


#include <stdio.h>


int i = 5;


int main (void)
{
printf ("%i ", i);


foo ();

printf ("%i\n", i);

return 0;
}

Free download pdf