The declaration below:
static int *foo();
declares foo
as a static function returning a pointer to an int
.
What's the purpose of declaring a function as static ?
The declaration below:
static int *foo();
declares foo
as a static function returning a pointer to an int
.
What's the purpose of declaring a function as static ?
Declaring a function as static
prevents other files from accessing it. In other words, it is only visible to the file it was declared in; a "local" function.
You could also relate static
(function declaration keyword, not variable) in C as private
in object-oriented languages.
See here for an example.
Marking a function or a global variable as static
makes it invisible to the linker once the current translation unit is compiled into an object file.
In other words, it only has internal linkage within the current translation unit. When not using static
or explicitly using the extern
storage class specifier, the symbol has external linkage.
From the C99 standard:
6.2.2 Linkages of identifiers
If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.
and
In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. Each declaration of an identifier with no linkage denotes a unique entity.
The function's name isn't visible outside the translation unit (source file) in which it's declared, and won't conflict with another function
foo
in another source file.In general, functions should probably be declared
static
unless you have a specific need to call it from another source file.(Note that it's only the name that's not visible. It can still be called from anywhere in the program via a pointer.)