Jiwon
Jiwon

Reputation: 1218

Can I dynamically link libraries that have duplicated name of functions?

Imagine that Library1.so and Library2.so has:

func1(), func2(), glob_data1, glob_data2  


Situation:
I want use func1() and glob_data1 in Library1,
and simultaneously use func2() and glob_data2 in Library2.


Question:
How can I do that when I dynamically link those libraries?
(If there's no way on C level, Is there any possible way on assembly level?)

Upvotes: 0

Views: 50

Answers (2)

Employed Russian
Employed Russian

Reputation: 213456

Imagine that Library1.so and Library2.so has: func1(), func2(), glob_data1, glob_data2

It is generally a very bad idea to load both libraries into a single process on Linux (and other UNIX systems).

When e.g. func1 from library1 calls func2, which func2 gets called? The answer depends on exactly how the libraries were linked, how they were loaded, and in which order.

If the functions don't call any other exported symbols, you can call them via a function pointer obtained from dlopen and dlsym:

void *h1 = dlopen("Library1.so", RTLD_LOCAL|RTLD_LAZY);
int (*f1L1)(void) = dlsym(h1, "func1");

void *h2 = dlopen("Library2.so", RTLD_LOCAL|RTLD_LAZY);
int (*f1L2)(void) = dlsym(h2, "func1");

printf("func1 from Library1 returns %d\n", f1L1());
printf("func1 from Library2 returns %d\n", f1L2());

Upvotes: 2

yugr
yugr

Reputation: 21878

If these symbols are not meant for use outside of the libraries you can simply mark them as __attribute((visibility("hidden"))) (or better yet compile your code with -fvisibility=hidden and annotate public functions with __attribute((visibility("default")))).

If these functions have to remain public you can link your libs with -symbolic flag. This would cause linker to resolve references to local definitions (rather than PLT stubs) when possible.

Note that -symbolic applies to all library symbols. It's possible to achieve the same effect for a subset of symbols using symbol aliases but this is more involved so I'd rather not go into details unless you really need it.

Upvotes: 1

Related Questions