Programming in C

(Barry) #1
Communication Between Modules 339

StaticVe r sus ExternVa riables and Functions


You now know that any variable defined outside of a function is not only a global vari-
able, but is also an external variable. Many situations arise in which you want to define a
variable to be global but notexternal. In other words, you want to define a global vari-
able to be local to a particular module (file). It makes sense to want to define a variable
this way if no functions other than those contained inside a particular file need access to
the particular variable.This can be accomplished in C by defining the variable to be
static.
The statement


static int moveNumber = 0;


if made outside of any function, makes the value of moveNumberaccessible from any sub-
sequent point in the file in which the definition appears,but not from functions contained in
other files.
If you need to define a global variable whose value does not have to be accessed from
another file, declare the variable to be static.This is a cleaner approach to program-
ming:The staticdeclaration more accurately reflects the variable’s usage and no con-
flicts can be created by two modules that unknowingly both use different external global
variables of the same name.
As mentioned earlier in this chapter, you can directly call a function defined in
another file. Unlike variables, no special mechanisms are required; that is, to call a func-
tion contained in another file, you don’t need an externdeclaration for that function.
When a function is defined, it can be declared to be externor static, the former
case being the default. A static function can be called only from within the same file as
the function appears. So, if you have a function called squareRoot, placing the keyword
staticbefore the function header declaration for this function makes it callable only
from within the file in which it is defined:


static double squareRoot (double x)
{
...
}


The definition of the squareRootfunction effectively becomes local to the file in which
it is defined. It cannot be called from outside the file.
The same motivations previously cited for using static variables also apply to the case
of static functions.
Figure 15.1 summarizes communication between different modules. Here two mod-
ules are depicted,mod1.cand mod2.c.
mod1.cdefines two functions:doSquareand main.The way things are set up here,
maincalls doSquare, which in turn calls square.This last function is defined in the
module mod2.c.
Because doSquareis declared static, it can only be called from within mod1.c, and
by no other module.

Free download pdf