Search code examples
symbolsdlopendynamic-libraryundefined-symbol

Check if a symbol is available, to prevent dlopen lazy binding failure


I load a .so library using dlopen(). The library calls myfunc(). The function is available in version 1.0 of the loader. So calling myfunc() works. In version 0.9 however, there is no myfunc(), and libdl shows error about lazy binding failure.

Can I, within the so. library, check if myfunc() exists, and only then call the function? The function is not mandatory, not important, I can safely skip calling it if loader is in version 0.9 or lower.


Solution

  • On and ELF platform, you can use weak unresolved reference to achieve your goal:

    // libfoo.c
    extern int myfunc() __attribute__((weak));
    int foo()
    {
       if (&myfunc == NULL) {
         printf("myfunc is not defined\n");
       } else {
         // myfunc is available, call it
         printf ("myfunc returns %d\n", myfunc());
       }
    }