0

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?
}
4
  • 1
    You're giving the function internal linkage then wonder why you can't call it externally? Is this a real question? Commented Feb 11, 2012 at 13:44
  • Does your fun() defined in header file? Commented Feb 11, 2012 at 13:44
  • It works fine for me (after fixing main to return int). You can access functions with internal linkage from different files so long as all those files are #included into the same translation unit. Commented Feb 11, 2012 at 13:46
  • fun() is declared in abc.h and defined in abc.cpp Commented Feb 11, 2012 at 13:47

2 Answers 2

4

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.

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

1 Comment

"Most C/C++ compilers do this by mangling the function name with the source file name." I think you're thinking of anonymous namespaces.
0

You can pass the function pointer ( of your static function ) and use it across files.

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.