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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With