Reputation: 1
I am a little confused on the purpose of static functions in C, if anybody can explain that would be great! :)
I understand that static functions are used to limit the function’s visibility but why is it used?
Upvotes: 0
Views: 89
Reputation: 222724
Large programs are built with multiples subcomponents, which may be in separate groups of source files within one company or in libraries provided by third-party vendors.
When a function is not declared with static
, its identifier has external linkage. This means any two instances of the identifier will be linked to refer to the same function.
Sometimes we do not want that. One person writing something for one part of the program might have called one function they use CalculateSquare
because it calculates the square of a complex number, and another person writing something for another part of the program might have called a function CalculateSquare
because it calculates some properties for a geometric square. If both of these identifiers have external linkage, this will generally result in a link error due to multiple definitions or, worse, linking in one definition and not the other with no error message (which can happen when one is in a library file).
When a function is declared with static
, its identifier has internal linkage. This means uses of its identifier inside the same translation unit, after its declaration, will refer to that function, but uses of the same identifier in other translation units will not refer to the function in this translation unit. This allows programmers to pick their names more freely, without worrying about collisions with names other programmers use.
(There are other ways to avoid multiple definition errors. Linkers often have commands to control the publication and use of symbols in their output files, and those sometimes have to be used and may provide features that merely using static
does not. However, using static
is a standard and easy way to handle this in many situations.)
Upvotes: 4