Home Segments Index Top Previous Next

683: Sidetrip

Of course, there are occasions when you want to keep the global variables in one file out of the way of the global variables in another file.

Suppose, for example, that you and a partner have divided into two parts the work of writing a program. Each of you works on a file full of functions. Both of you have employed a global variable named, accidentally, hack. Ordinarily, your separate use of that variable name will lead your C compiler to note a multiple-variable–definition error when those files are linked together.

Fortunately, if you add static to the definition of a global variable, then the value of that global variable is accessible to only those functions defined in the same file.

Accordingly, one or both of you can define the variable to be static:

The hack variable is defined as a static global variable in this file 
  | 
  |                     A different static global hack variable is  
  |                     defined in this file 
  |                       |                  
  v                       v                       
*------------------*    *------------------* 
| static int hack; |    | static int hack; | 
|                  |    |                  | 
*------------------*    *------------------* 

Because of the use of static in the variable definitions, the variables keep out of each other's way.