I have a static method in a cpp file (not in class) . I want to use it globally without redeclaring it as extern . In that case is it possible to use a global function pointer to this static method and use this function pointer globally ??
5 Answers
The static declaration in C tells the compiler not to to add the function the symbol table. This means that the inker has no way to link that function in if needed by other modules. The function will still exists (but is invisible to the linker) so if one records the address of the function in a pointer one will be able to call the function with no problem.
So short answer is yes, it is ok.
1 Comment
static function to do the work, but why not make the original function in the first place?Yes, making a public pointer while hiding the implementation is generally what you might expect in a factory style pattern.
It might be interesting to know why you say "I want to use it globally without redeclaring it as extern ."
Why is changing the declaration from static (making it available in that module only) to extern (making it available outside the module and publishing it) an action you want to avoid?
Comments
If it is static in a cpp file in the global namespace, then the function can only be used directly from within that cpp file. It is a kind of private helper function.
What you can do is to make a typedef on the function's prototype and introduce a public function that returns a pointer to the function or a table of pointers to different functions, which is often done in order to implement plug-ins and have some callbacks or api methods registered. + point is that you do not have a strong binding to the function.
Comments
the static specifier implies internal linkage.
You want static with external linkage, which does not require an explicit storage specifier. If your function is at namespace scope, simply remove the 'static' specifier. The default behavior at namespace scope is static with external linkage.