Tutorials/Dynamic libraries in C
From ThorstensHome
(Redirected from Dynamic libraries in C)
This article demonstrates dynamic linking in C. It creates a shared library and then a program that uses it.
Load during run-time
libdl is a library for dynamic loading during runtime.
main.cpp
#include <iostream>
#include <dlfcn.h>
int main()
{
void* sym = dlopen("./help.so", RTLD_LAZY);
typedef void (*help_t)();
dlerror();
help_t help = (help_t) dlsym(sym, "help");
const char *dlsym_error = dlerror();
help();
dlclose(sym);
}
help.cpp
#include <iostream>
extern "C" void help()
{
std::cout << "hello world" << '\n';
}
Compile, link and run it
scorpio:~ # gcc help.cpp -o help.so -ldl -shared -fPIC scorpio:~ # g++ main.cpp -ldl scorpio:~ # ./a.out
Load before run-time
Use the stuff from above, then change main.cpp to be:
main.cpp
#include <iostream>
#include <dlfcn.h>
extern "C" void help();
int main()
{
help();
}
We declare the function help, but do not implement it. This means, the compiler knows which parameters the function will have, but has to take it from external.
Compile, link and run
cp help.so libhelp.so cp libhelp.so /usr/lib g++ main.cpp -lhelp
Verify it is really needing a shared object file
tweedleburg:~/test # ldd a.out
linux-vdso.so.1 => (0x00007fff33dfe000)
libhelp.so => not found
libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x00007fe42b888000)
libm.so.6 => /lib64/libm.so.6 (0x00007fe42b632000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007fe42b41b000)
libc.so.6 => /lib64/libc.so.6 (0x00007fe42b0c2000)
/lib64/ld-linux-x86-64.so.2 (0x00007fe42bb94000)
Tell the loader where to search for the shared lib:
tweedleburg:~/test # export LD_LIBRARY_PATH=.
tweedleburg:~/test # ldd a.out
linux-vdso.so.1 => (0x00007fff8fffe000)
libhelp.so => ./libhelp.so (0x00007fb387bcf000)
libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x00007fb3878c3000)
libm.so.6 => /lib64/libm.so.6 (0x00007fb38766d000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007fb387456000)
libc.so.6 => /lib64/libc.so.6 (0x00007fb3870fd000)
libdl.so.2 => /lib64/libdl.so.2 (0x00007fb386ef9000)
/lib64/ld-linux-x86-64.so.2 (0x00007fb387dd1000)
tweedleburg:~/test # ./a.out
hello world