/* * simple program illustrating dynamic loading of library functions. */ #include #include #include void foo(void); void bar(void); void dynamic_call(void * lib_handle, char * name); int main(void) { void *lib_handle; lib_handle = dlopen("libtest_s.so", RTLD_LAZY); if (!lib_handle) { fprintf(stderr, "%s\n", dlerror()); return 1; } dynamic_call(lib_handle, "foo"); dynamic_call(lib_handle, "bar"); dynamic_call(lib_handle, "foobar"); dynamic_call(lib_handle, "foo"); dynamic_call(lib_handle, "bar"); printf("that's all, folks!\n"); return 0; } void dynamic_call(void * lib_handle, char * name) { void (*fcn)(void); char *error; printf("calling %s\n", name); /* * strictly speaking, this is not good C -- dlsym returns a "void *", and * C doesn't guarantee that that can be converted to a function pointer -- * but the POSIX standard says it can, so live with the warning, I guess. */ fcn = dlsym(lib_handle, name); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); } else { (*fcn)(); } }