Static Functions in C (original) (raw)
Last Updated : 02 Jan, 2025
In C, functions are global by default. The **static keyword before a function name makes it a static function. For example, the below function fun() is static.
C `
#include <stdio.h>
static int fun(void) { printf("I am a static function "); }
int main() { fun(); return 0; }
`
Output
I am a static function
Unlike global functions in C, access to static functions is restricted to the file (or translation unit) where they are declared (internal linkage). Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be the reuse of the same function name in other files.
Syntax of static Function
We just add the keyword static before the function prototype/declaration.
**static return_type name(args) {
// Function body
}
Applications of static Function
The primary application of static function is to limit its scope to the translation unit where they are declared. This helps in achieving two things:
- Data hiding as we can hide the function from other translation units or files.
- Avoiding function name clashes in multi-file programs.
**Example of static Function
We need a multifile program to see the effects of static function.
Let's consider a C source file **src.c that have a function **calc() that should be available to all translation unit. But this function internally calls another function **sum() to get the results. We need to hide the sum from other files. To do that, we can declare it as a static.
**src.c
C `
// Available to only this translation unit static int sum(int a, int b) { return a + b; }
// Available to every translation unit int calc(int a, int b) { return sum(a, b); }
`
Another file named main.c uses the calc() function.
**main.c
C `
#include <stdio.h>
// Informing about the existance of calc() in another file extern int calc(int a, int b);
int main() {
// Using calc()
printf("10 + 20 = %d", calc(10, 20));
return 0;
}
`
Compiling and executing this program in GCC using following command:
gcc main.c src.c -o main
./main
We get the output:
10 + 20 = 30
But what happens if we try to access the **sum() function directly? Let's change the main.c and try again.
**main.c
C `
#include <stdio.h>
// Informing about the existance of sum() in another file extern int sum(int a, int b);
int main() {
// Using calc()
printf("10 + 20 = %d", sum(10, 20));
return 0;
}
`
Compiling this in the same environment, we get this error:
main.c:(.text+0x6c): undefined reference to `sum'
We were not able to access the sum() function outside the src.c file because it was declared as static.