338 Chapter 15 Working with Larger Programs
The definition of the global variable iin the preceding program makes its value accessi-
ble by any module that uses an appropriate externdeclaration. Suppose you now type
the following statements into a file called foo.c:
extern int i;
void foo (void)
{
i = 100;
}
Compiling the two modules main.cand foo.ctogether with a command like
$ gcc main.c foo.c
and subsequently executing the program produces the following output at the terminal:
5 100
This output verifies that the function foois able to access and change the value of the
external variable i.
Because the value of the external variable iis referenced insidethe function foo,you
could have placed the externdeclaration of iinside the function itself, as follows:
void foo (void)
{
extern int i;
i = 100;
}
If many functions in the file foo.cneed to access the value of i, it is easier to make the
externdeclaration just once at the front of the file. However, if only one function or a
small number of functions need to access this variable, there is something to be said for
making separate externdeclarations in each such function: It makes the program more
organized and isolates the use of the particular variable to those functions that actually
use it.
When declaring an external array, it is not necessary to give its size.Thus, the
declaration
extern char text[];
enables you to reference a character array textthat is defined elsewhere. As with formal
parameter arrays, if the external array is multidimensional, all but the first dimension
must be specified.Thus, the declaration
extern int matrix[][50];
suffices to declare a two-dimensional external array matrixthat contains 50 columns.