Hi everyone
Is there a real need to use keyword static with functions, if we
simply don't declare their prototypes in .h file?
Many textbooks avoid to discuss this matter and/or discuss only the
usage of static functions. I've been programming for years and I never
felt a real need for the "static approach for functions".
I don't know if this is a trivial matter since the reserved word
exists.
Or it exists for some other purpose I can't figure out.
What did I have missed?
Thanks in advance for answers
In C, functions can have one of two types of linkage: external or
internal.
A function with external linkage can be defined only once and called
by multiple translation units, while a function with internal linkage
can be defined once for each translation unit and called (directly)
only by the translation unit that defines it (separate translation
units that define the same function with internal linkage effectively
get their own copy of the function definition).
The keyword static, when used in a function prototype or definition,
implies internal linkage, while the keyword extern (or lack of both
extern and static) in a function prototype or definition, implies
external linkage
All functions should have a prototype in scope, with the exception of
main().
Function prototypes declared in a .h file should not be declared as
static; you can declare them as extern, but that's not necessary.
/* foo.h */
static void foo1(void); /* bad */
void foo2(void); /* okay */
extern foo3(void); /* okay, though use of extern is superfluous */
Function prototypes declared in a .c file should use static. The
function definition whose prototype is declared with static can also
use static (but not extern), but that's not necessary, although it's
good practice.
/* foo.c */
static void foo4(void);
#ifdef DEFS_WITH_STATIC
static void foo4(void) /* okay */
{
/* implement foo4 */
}
#else
void foo4(void) /* okay */
{
/* implement foo4 */
}
#endif
Likewise, function definitions whose prototype is not declared with
static can also use extern (but not static), but that's not necessary,
although it's considered acceptable by some and suspect by others
(PC-lint falls into the latter category).
/* foo.c */
#include "foo.h"
#ifdef DEFS_WITH_EXTERN
extern void foo2(void) /* okay */
{
/* implement foo2 */
}
#else
void foo2(void) /* okay */
{
/* implement foo2 */
}
#endif
One argument for not using extern with function definitions is that
you can "grep" a .c source file for "extern" and expect to find no
matches.
Regards