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 the work of
writing a program into two parts. Each of you works on a file full of
functions. Both of you have employed a global variable named,
accidentally, mode
. Ordinarily, your separate use of that variable
name will lead your C++ compiler to note a multiple-variabledefinition
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 mode variable is defined as a static global variable in this file | | Different static global mode variable is | defined in this file | | v v *------------------* *------------------* | static int mode; | | static int mode; | | | | | | | | | | | | | *------------------* *------------------*
Because of the use of static
in the variable definitions,
the variables keep out of each other's way.