#include <stddef.h> #include <stdbool.h> #include <stdio.h> #include <dlfcn.h> bool init_library(void *hdl, void(*print_hello)(const char *)) { hdl = dlopen("./libHello.so", RTLD_LAZY); if (NULL == hdl) return false; print_hello = (void(*)(const char *)) dlsym(hdl, "print_hello"); if(NULL == print_hello) return false; return true; } int main() { void (*print_hello)(const char *); void *hdl; if(init_library(hdl, print_hello)) print_hello("Vasya"); else printf("Library was not loaded\n"); dlclose(hdl); return 0; } compile so gcc main.c -ldl -o exe eventually segmented error. even if you put printf ("1 \ n"); at the beginning of the main - anyway segmentation error.
hello.c code
#include <stdio.h> #include "hello.h" void print_hello(const char *name) { printf("Hello, %s!\n", name); } hello.h code
#ifndef __HELLO__ #define __HELLO__ void print_hello(const char *name); #endif Makefile for libHello.so
libHello: hello.h hello.c gcc -shared hello.c -fPIC -o libHello.so the following code is executed without error
#include <stddef.h> #include <stdbool.h> #include <stdio.h> #include <dlfcn.h> int main() { void *hdl; hdl = dlopen("./libHello.so", RTLD_LAZY); void (*print_hello)(const char *); print_hello = (void(*)(const char *)) dlsym(hdl, "print_hello"); print_hello("Vasya"); dlclose(hdl); return 0; } compile gcc main.c -ldl -o exe