main.c
# gcc -o main main.c -ldl
#include <stdio.h> #include <string.h> #include <stdlib.h> // Header files needed to include #include <dlfcn.h> typedef int (*func_ptr_t)(int, int); // Use absolute path const char* so_path = "/home/ojenv_c/lib/libtongyishu.so"; // Need to specify library when compiling : -ldl int main() { // Open failed return NULL // RTLD_LAZ // RTLD_NOW // RTLD_GLOBAL // RTLD_LOCAL void* handle = dlopen(so_path, RTLD_NOW); if (handle == NULL) { fprintf(stderr, "[error] Open so error. "); return -1; } // Second parameter is function name func_ptr_t fptr = dlsym(handle, "tongyishu_add"); fprintf(stdout, "%d ", fptr(1, 2)); dlclose(handle); return 0; }
a.c
# gcc -fPIC -shared -o libtongyishu.so a.c
#include <stdlib.h> int tongyishu_add(int a, int b) { return a + b; }