简体   繁体   中英

How to load static function (in C) from a dynamic library on Linux

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.)

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 (ie 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM