Static Variables
In our last episode we looked at
the
extern
keyword and how it's used with global
variables. Today we'll look at using the static
keyword to make global variables "private" to one .m
or
.c
file.
By default, every global variable in a .m
or
.c
file is external or "public". After each
.m
or .c
file is compiled, the linker
combines them together and matches up every global variable declaration
with its corresponding definition. If a definition is missing, or a
global variable is defined more than once, the linker generates an
error.
But sometimes you want a global variable that's only "global" to one
.m
or .c
file. For example, you might have
two similar UIView
subclasses that each use a global
variable named defaultHeight
:
// ERROR: won't link
// CoolView.m
// ...
CGFloat defaultHeight = 400.0f;
// ...
// HotView.m
// ...
CGFloat defaultHeight = 300.0f; // ERROR: duplicate global variable definition
// ...
The linker sees the same global variable name defined in two different
.m
files and fails with an error. One solution is to give
the variables unique names, like coolViewDefaultHeight
and
hotViewDefaultHeight
. But if you don't need to use those
global variables outside the .m
file, you can make them
static
instead.
When used with a global variable, the static
keyword makes
the global variable "private" to the .m
or .c
file where it's defined. So our example would look like:
// CoolView.m
// ...
static CGFloat defaultHeight = 400.0f; // only visible in CoolView.m
// ...
// HotView.m
// ...
static CGFloat defaultHeight = 300.0f; // only visible in HotView.m
// ...
Using static
where possible helps you avoid name
collisions in larger programs. Next time, we'll look at using
static
to make a global variable visible only within a single function or
method.