I know about the static
keyword in C before a function declaration to only allow the file it is declared at to use the function (the compilation unit, to be more precise). I've done some research and I have found already answered questions regarding including them in headers, and what it does in detail, but I have one that I think is missing:
Does the static
keyword add anything to a program, when there's no other declaration of a function but the one followed by its definition ?
e.g. :
main.c
#include "foo.h"
int main () {
foo();
return 0;
}
foo.c
void foo2() {
return ;
}
void foo() {
return foo2();
}
foo.h
void foo();
What would be the difference if foo2()
was declared as static void
?
CodePudding user response:
When we have an application written by multiple people, and one person defined a function square
to compute the mathematical square of a number and another person defined a function square
to draw a square on a display, then, if neither function is defined with static
, linking the program may result in a multiple-definition error. When the functions are defined with static
, this multiple-definition error will not occur, because the same name will not be exported from multiple object files.
If there is only one definition of the name in the entire program, then no such multiple-definition error should occur. However, if the function is declared static
, the compiler knows it does not have to export a definition. This means that, if the compiler “inlines” the function into all the locations that call it, it does not have to emit assembly code for a separate implementation of the function. (Inlining a function is the process of incorporating its code into the place where it is called, instead of using a call instruction to call the function.)