Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a static function be called through a function pointer in C?

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 ?

like image 287
AnkurVj Avatar asked Nov 05 '11 20:11

AnkurVj


People also ask

Can we use a pointer with static function?

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).

Can we call a function using pointer?

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.

How can a static function be called in main 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.

Can I return pointer to static variable?

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.


2 Answers

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.

like image 57
Crashworks Avatar answered Oct 25 '22 21:10

Crashworks


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.

like image 35
cnicutar Avatar answered Oct 25 '22 22:10

cnicutar