Hardware Reference
In-Depth Information
many functions. Because external variables are globally accessible, they provide an alternative
to functional arguments and return values for communicating data between functions. Any
function may access an external variable by referring to it by name, if the name has been de-
clared somehow. External variables are also useful when two functions must share some data,
yet neither calls the other.
The use of static with a local variable declaration inside a block or a function causes the
variable to maintain its value between entrances to the block or function. Internal static vari-
ables are local to a particular function just as automatic variables are, but unlike automatic
variables, they remain in existence rather than coming and going each time the function is
activated. When a variable is declared static outside of all functions, its scope is limited to the
file that contains the definition. A function can also be declared as static. When a function is
declared as static, it becomes invisible outside of the file that defines the function.
A volatile variable has a value that can be changed by something other than the user code. A
typical example is an input port or a timer register. These variables must be declared as volatile so
the compiler makes no assumptions on their values while performing optimizations. The keyword
volatile prevents the compiler from removing apparently redundant references through the pointer.
5.9.2 Scope Rules
The functions and external variables that make up a C program need not all be compiled at
the same time; the source text of the program may be kept in several files, and previously com-
piled routines may be loaded from libraries.
The scope of a name is the part of the program within which the name can be used. For a
variable declared at the beginning of a function, the scope is the function in which the name is
declared. Local (internal) variables of the same name in different functions are unrelated.
The scope of an external variable or a function lasts from the point at which it is declared
to the end of the file being compiled. Consider the following program segment:
. . .
void f1 (. . .)
{
. . .
}
int a, b, c;
void f2 (. . .)
{
. . .
}
Variables a , b , and c are accessible to function f 2 but not to f 1 .
When a C program is split into several files, it is convenient to put all global variables into
one file so that they can be accessed by functions in different files. Functions residing in differ-
ent files that need to access global variables must declare them as external variables. In addi-
tion, the prototypes of certain functions can be placed in one file so that they can be called by
functions in other files. The following example is a skeletal outline of a two-file C program that
makes use of external variables:
In fi le1 :
extern int xy;
extern long arr[];
main ( )
 
Search WWH ::




Custom Search