Load libraries dynamically runtime
1 min readJun 26, 2021
C++ linux
Application
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h> // for dlopen, dlsym, dlcloseint main(int argc, char** argv) {
if (argc < 3) {
printf("usage: %s <library> <number>\n", argv[0]);
exit(1);
} char* libPath = argv[1];
int number = atoi(argv[2]); void* libHandle = dlopen(libPath, RTLD_LAZY);
if (libHandle == nullptr) {
perror("dlopen failed");
exit(1);
} typedef int (*func)(int);
func f;
f = (func)dlsym(libHandle, "perform");
if (f == nullptr) {
perror("dlsym failed");
exit(1);
}
printf("%d --> %d\n", number, f(number));
dlclose(libHandle); return 0;
}
Library
extern "C" {
// C++ mangles function name. So, "C" binding is required to search a function for dlsym
int perform(int i);
}const char* getLibraryName() {
return "add1";
}int perform(int i) {
return i+1;
}
Makefile
make sure to add `-Wl, — no-as-needed -ldl`
CC=g++
CFLAGS=-Wall -g
BINS=libplus1.so test.elfall: $(BINS)%.so: %.cpp
$(CC) $(CFLAGS) -fPIC -shared -o $@ $^%.elf: %.cpp
$(CC) $(CFLAGS) -Wl,--no-as-needed -ldl -o $@ $^clean:
rm $(BINS)
rm -r *.so
Run
$ ./test.elf ./libplus1.so 4
4 --> 5