I was reading about static functions in C on this thread: https://stackoverflow.com/a/558201/7997108
As i understood it, basically where you define the static functions is the only "place"/file (fileA.c i.e.) where you can call it, which kinda makes this function "private" to that .c or .h file (or translation unit). But if you #include this file in some other (fileB.c) you will still be able to use it there as well?
So im trying to understand in which case you want the function to be static to its own .c and how it makes sense if you can still use that "private"/static function by just including the file where it is defined.
Also as i understand, in case you don't include some other file where some function is defined you won't be able to use/call that function anyways right?
In other words i just cant comprehend what is the typical use-case for static functions and how is it different from non-static function basically.
2 Answers 2
Imagine you're coding a library and you need to define a little helper function. Maybe you name this function test:
int test(int x)
{
return x > 100;
}
This function isn't part of the public interface, so you leave it tucked away inside the .c file. And everything is good right?
Wrong.
Problem #1: Anyone can use this function simply by adding this declaration to their code:
int test(int);
Problem #2: Imagine if another library had their own test helper function. If that library and your library were used in the same program, the linker would error because two functions can't have the same name.
The solution is to use static. With static, the functions are unique to their translation unit and aren't exposed globally.
8 Comments
static function in a header file would be recompiled every time that header is included. That's not a good thing - it's wasteful!static inline functions that won't get a public visible name.Static functions in C usually used to separate an interface and its implementation. They play role of implementations that are not visible to clients of interfaces. On the other hand non-static functions play role of interfaces and are visible to clients of the functions.
staticfunctions that are only called once to have their own file but don't want them to have global symbols, I separate them into their own.cfile and#includethem from where I want to use them.staticfunction in a header (.h) file would define a "private" function of the same name and with the same implementation in every translation unit that includes this header file. This will duplicate the code. If you#includea source file (A.c) with the definition of astaticfunction in another source file (B.c) and compile both A.c and B.c you will also get duplicate copies of the same "private" function in both translation units.