1

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 ??

0

5 Answers 5

6

It is possible to do what you want, but why would you avoid using extern when it does exactly what you are trying to emulate through a much more convoluted (and unreadable) mechanism?

Sign up to request clarification or add additional context in comments.

Comments

1

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

...or you can write an extra function with a public name that simply calls the static function to do the work, but why not make the original function in the first place?
0

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

0

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

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.