Reputation: 21
I have a static function "foo" in a dynamic library foolib. I am successfully able to load foolib in my application. Although dlsym returns NULL for "foo"
Even nm utility doesn't list static function as an exportable symbol.
I understand that static function has scope limited to that file.
Still, is there any way to achieve this.
I know this is possible in C++, don't know how and why (may be shared library is treated as object and functions within that library as interfaces.)
Upvotes: 2
Views: 5554
Reputation: 126787
static
is not just a "scoping" thing - static
functions have internal linkage, so no information about their existence is written by the compiler in the object file; such information cannot be recovered later (while creating the dynamic library).
Even better: if it's a small function it will probably be inlined in every circumstance, and, since it has internal linkage, there will be no need to generate the "standalone" version, so the function will actually not exist anymore after the compilation stage.
The only practical way I see to get an address to such a function "from the outside" would be to have another function in the same translation unit (i.e. in the same .cpp file) that returns a pointer to the foo
function, and then export such helper function. Doable, but pretty pointless if you ask to me. :)
// In foolib
// The static function
static void foo()
{
// ...
}
// Typedef for the function pointer
typedef void (* fooFuncPtr)();
// Helper function to be exported - returns the address of foo
fooFuncPtr fooHelper()
{
return &foo;
}
typedef void (* fooFuncPtr)();
typedef fooFuncPtr (* fooHelperFuncPtr)();
// In the client code of foolib
// ...
fooHelperFuncPtr fooHelper = (fooHelperFuncPtr) dlsym(handle, "fooHelper");
// ... in real code here you would have error checking ...
fooFuncPtr foo = fooHelper();
// now you can use foo
foo();
Upvotes: 6