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

AnkurVj picture AnkurVj · Nov 5, 2011 · Viewed 16.7k times · Source

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 ?

Answer

Crashworks picture Crashworks · Nov 5, 2011

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.