Visibility in Multiple Source Files

A “source file” is the file containing your program's text. Source files normally have the .C file extension, to distinguish them from other files such as executable (.EXE) files.

Simple programs have only one source file, but large programs are often split into several source files. If you write a word-processing program, for instance, you might place all the program's screen-output functions in one file, all the file-handling functions in a second file, and so forth.

Summary: Use the extern keyword to make an external variable visible in more than one source file.

Normally, an external variable is visible only in the source file in which it is declared. In a multi-file program, however, a function in one file might need to access a variable in a second file. To make the variable visible in more than one source file, you must declare it with the extern keyword.

Let's look at a short two-file program that shows how to use extern. The first source file, FILE1.C, declares two external variables, chico and harpo. The file contains one function (main) that calls a second function named yonder.

/* FILE1.C: Visibility in multiple source files. */

int chico = 20, harpo = 30;

extern void yonder( void );

main()

{

yonder();

}

The second source file, FILE2.C, contains the yonder function that is called in FILE1.C. This file also declares the variables chico and harpo, but it prefaces their declarations with extern to show that the variables are defined externally in some other file. Once this is done, any function in FILE2.C can refer to chico and harpo as if they are defined in the same file.

/* FILE2.C: Visibility in multiple source files. */

#include <stdio.h>

void yonder( void )

{

extern int chico, harpo;

printf( "chico = %d, harpo = %d\n", chico, harpo );

}

To compile this program in the QuickC environment, choose Open from the Project menu and add FILE1.C and FILE2.C to the list. Next, choose Project from the Options menu. Select QuickWin EXE for the Program Type. Then choose Build from the Project menu.

The executable file is named FILE1.EXE. The program's output,

chico = 20, harpo = 30

shows that the yonder function in FILE2.C can access the variables defined in FILE1.C.

Sometimes you may want an external variable to be visible only in the source file where it's declared. The variable can be shared by functions in one file, but it is hidden to all other files, thus minimizing the risk of naming conflicts.

Summary: The static keyword can limit a variable's visibility to one source file.

To limit a variable's visibility to one file, precede the variable's declaration with the keyword static. For example, if FILE1.C declared the harpo variable as static in this manner,

static int harpo;

it would prevent FILE2.C from accessing harpo at all, even though FILE2.C declares (with extern) that harpo is defined somewhere else.