What is the advantage of a static function?

10.5k views Asked by At

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 ?

5

There are 5 answers

2
Keith Thompson On BEST ANSWER

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.)

0
cnicutar On

It prevents other translation units (.c files) from seeing the function. Keeps things clean and tidy. A function without static is extern by default (is visible to other modules).

3
Evan Mulawski On

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.

0
Blagovest Buyukliev On

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.

0
znkr On

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.