Can we access static functions defined in one file to another file?
In the code below, I cannot call the static method fun(). Why can’t I and is there another way to access it?
static void fun();// In abc.h
static void fun(){cout<<"Hello."<<endl;}
//xyz.cpp
#include "abc.h"
void main()
{
fun();// Why I am not able to call this static method? Is there any other way to
//Access this static function?
}
Because that’s how
static(on free functions and global variables) works. It’s supposed to do exactly this: limit access to the current compilation unit. Most C/C++ compilers do this by mangling the function name with the source file name.In theory, you could decompose the mangling, locate the mangled function in the executable at runtime, and do some assembly voodoo to force a function call, but this is going to be brittle, platform-dependent, and a general pain – I doubt you could bring it to practical use. Just don’t declare the function static if you want to call it from elsewhere.