As we know that the static function can not be accessed by the other source file but is there any way to use the static function from one source file to another source file without making it global?
Asked
Active
Viewed 58 times
1
-
`#include "staticfuncfile.C"` – shrewmouse May 31 '21 at 16:20
-
2@shrewmouse Please don't give such advises without further elaboration. This is only inviting troubles if used without understanding. – Eugene Sh. May 31 '21 at 16:22
-
https://stackoverflow.com/questions/37442606/calling-a-function-with-internal-linkage-via-pointer-from-another-translation-un?r=SearchResults it's about C++ but the concept applies here as well – bolov May 31 '21 at 16:40
2 Answers
3
You can make the function available to other translation units via a function pointer returned from another function.
In a header file you would have the following:
typedef void (*ftype)(void);
ftype getHidden(void);
Then in a souce file you would have:
static void hidden(void)
{
printf("in hidden\n");
}
ftype getHidden(void)
{
return hidden;
}
Now other translation units can call getHidden
to get a pointer to the static function that can be called.

dbush
- 205,898
- 23
- 218
- 273
-
-
@Aerie Glad I could help. Feel free to [accept this answer](https://stackoverflow.com/help/accepted-answer) if you found it useful. – dbush May 31 '21 at 16:34
0
Not without copying it. The whole purpose of a static function within a file is to "hide" it from other files so you avoid name space collisions.

Wes Hardaker
- 21,735
- 2
- 38
- 69
-
How does `qsort` call the comparison function passed to it if the identifier for the comparison function is declared `static`? – Eric Postpischil May 31 '21 at 16:37