What static
does is make it impossible to declare and call a function in other modules, whether through a header file or not.
Recall that header file inclusion in C is just textual substitution:
// bar.c
#include "header.h"
int bar()
{
return foo() + foo();
}
// header.h
int foo(void);
gets preprocessed to become
int foo(void);
int bar()
{
return foo() + foo();
}
In fact, you can do away with header.h
and just write bar.c
this way in the first place. Similarly, the definition for foo
does not need to include the header in either case; including it just adds a check that the definition and declaration for foo
are consistent.
But if you were to change the implementation of foo
to
static int foo()
{
// whatever
return 42;
}
then the declaration of foo
would cease to work, in modules and in header files (since header files just get substituted into modules). Or actually, the declaration still "works", but it stops referring to your foo
function and the linker will complain about that when you try to call foo
.
The main reason to use static
is to prevent linker clashes: even if foo
and bar
were in the same module and nothing outside the module called foo
, if it weren't static
, it would still clash with any other non-static
function called foo
. The second reason is optimization: when a function is static
, the compiler knows exactly which parts of the program call it and with what arguments, so it can perform constant-folding, dead code elimination and/or inlining.