Reputation: 23
I have a library libxx and inside that library there is a static function foo(). I want to write another function bar() which uses the function foo() as a subroutine.
Is there any way to do it without writing bar() on the file which the function foo() sits on and rebuilding the library?
Upvotes: 0
Views: 3804
Reputation: 22348
Declaring a function static
within a translation unit (object file / library) pretty much invalidates any assertions about that function's implementation. It could be completely inlined. It might use short-cuts with the calling conventions that would be incorrect when called externally.
On some OS/ABIs, the function will not be 'visible' in the sense that a .globl
directive with ELF/Mach-O
would provide, and the linker will prevent it, or the loader won't resolve it. In a shared library, it might not preserve position-independence outside its local use. The point is, you just can't do this safely or portably.
In short, you need to recompile the function as non-static, i.e., a global / visible symbol in the library, or have a static version available to your bar()
function. Say, via static inline
.
Upvotes: 4
Reputation: 245
It sounds like you have the source code to libxx. If that's the case, and you'd like bar() to exist in the same library as foo() then you'll need to recompile libxx after adding bar() to it.
If your goal is to call libxx::foo() from another program/library then you can just link libxx to your other project (which has bar() in it). Once the library is linked to your main project all you need to do is call into the correct namespace and invoke foo(). Linking a library to your main project will require using a linker. Different development systems will have different ways of invoking the linker. For researching this further, I would advise that you search for "c++ linking to static library X" where X is your development system (ex: visual studio, xcode). I'm assuming this is a static library based on the tag you put on the question, but maybe you meant that foo() was a static method. It shouldn't matter if it's a static method or not, linking will work in the same way. If you are confused about what I mean when I write "static library" then maybe researching the difference between static and dynamically linked libraries will clarify.
Upvotes: 1
Reputation: 13085
Not within standard C/C++.
The function has an address which is callable or other functions which may allow the foo
to be called indirectly.
But these are bad solutions
Upvotes: 0