Static functions in C


A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.

An example that demonstrates this is given as follows −

There are two files first_file.c and second_file.c. The contents of these files are given as follows −

Contents of first_file.c

static void staticFunc(void)
{
   printf("Inside the static function staticFunc() ");
}

Contents of second_file.c

int main()
{
   staticFunc();
   return 0;
}

Now, if the above code is compiled then an error is obtained i.e “undefined reference to staticFunc()”. This happens as the function staticFunc() is a static function and it is only visible in its object file.

A program that demonstrates static functions in C is given as follows −

Example

#include <stdio.h>

static void staticFunc(void){
   printf("Inside the static function staticFunc() ");
}

int main()
{
   staticFunc();
   return 0;
}

Output

The output of the above program is as follows −

Inside the static function staticFunc()

In the above program, the function staticFunc() is a static function that prints ”Inside the static function staticFunc()”. The main() function calls staticFunc(). This program works correctly as the static function is called only from its own object file.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

19K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements