Handling symbol lookup errors at runtime using C

Suppose I have a dynamic library that exports three functions:

void lib_function(void);
void lib_extra_function(void);
int  lib_runtime_version(int v);

And lib_extra_function was added in version 2 of the library.

If an application that uses lib_extra_function is built on a system with library version 2 installed, and then run on a system that provides only version 1, "symbol lookup error: ./main: undefined symbol: lib_extra_function" dynamic linker error is raised once lib_extra_function is called.

However, if application tries to use version information provided by library and call lib_extra_function conditionally, no error is raised, even though lib_extra_function is still undefined.

voif f()
{
    if(lib_runtime_version() >= 2) {
        lib_extra_function();
    } else {
        // try some workaround
    }
}

Now, is this behavior mandated by any standard? If not, is it specific to Linux? How do linkers in other systems (OSX, BSD) behave?

Upvotes: 4

Views: 2014

Answers (1)

Employed Russian
Employed Russian

Reputation: 213486

Now, is this behavior mandated by any standard?

No.

If not, is it specific to Linux?

No. It's a behavior that is supported by systems that do lazy runtime symbol resolution.

In general you should avoid doing this:

if(lib_runtime_version() >= 2) {
    lib_extra_function();

for a few reasons:

  • it will not work at all on systems that do eager symbol resolutions,
  • it will explode if end-user sets LD_BIND_NOW (which is special case of above), and
  • it violates the DRY principle.

Instead, if a function is optionally provided, use dlsym to find out whether it is available:

p_extra = dlsym(..., "lib_extra_function");
if (p_extra != NULL) {
    ....

Upvotes: 3

Related Questions