I believe that a static function in a source file cannot be called directly from outside the file. However, if I somehow manage to get a pointer to this function into another file, can I then call this function from that file. If yes, is there any scenario when we would like to take this route as compared to simply making the function non-static ?
The 'this' pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. 'this' pointer is not available in static member functions as static member functions can be called without any object (with class name).
Like variables, instructions of a function are also stored in memory and have an address. A pointer pointing to the address of a function is called function pointer. A function pointer in C can be used to create function calls to the function they point to just like a normal function.
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.
Static Variables have a property of preserving their value even after they are out of their scope. So to execute the concept of returning a pointer from function in C you must define the local variable as a static variable.
Yes, you can export static functions by handing out pointers to them. This is a common means of implementing the Factory pattern in C, where you can hide the implementations of a whole bunch of functions from the modules that use them, and have a FuncPtr_t GetFunction( enum whichFunctionIWant)
that hands them out to consumers. That's how many dynamic linking implementations work.
However, if I somehow manage to get a pointer to this function into another file, can I then call this function from that file.
Yes, it's perfectly possible. The function isn't visible to the linker, but it's there in the executable. You can always jump to its address.
I am not sure about scenarios though. Maybe you want others to only call your function after they called some other function (non-static of course). So you have them obtain it, and then they can call it.
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