Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What is a “static” function in C?

The question was about plain c functions, not c++ static methods, as clarified in comments.

I understand what a static variable is, but what is a static function?

And why is it that if I declare a function, let's say void print_matrix, in let's say a.c (WITHOUT a.h) and include "a.c" - I get "print_matrix@@....) already defined in a.obj", BUT if I declare it as static void print_matrix then it compiles?
by

2 Answers

rahul07
A static function is one that can be called on the class itself, as opposed to an instance of the class.

For example a non-static would be:

Person tom = new Person();
tom->setName("Tom");

This method works on an instance of the class, not the class itself. However you can have a static method that can work without having an instance. This is sometimes used in the Factory pattern:

Person
tom = Person::createNewPerson();
RoliMishra
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 a static function by placing the static keyword before the function name.

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.

Login / Signup to Answer the Question.