A variant of Carey's answer, in case you're on a *nix system. dlopen()
opens up your library. RTLD_LAZY
tells the loader to not bother resolving all the library's symbols right away, and to wait for you to try to access them. dlsym()
looks up the symbol in question.
Edit: Updated the snippet to better fit your clarification:
#include <dlfcn.h>
int main(int argc, char *argv[])
{
void *handle = dlopen("libexample.so", RTLD_LAZY);
if (handle == NULL) {
// error
}
char fct_name[64];
// read input from terminal here
void *func = dlsym(handle, fct_name);
if (func != NULL) {
// call function here; need to cast as appropriate type
}
}
libexample.so would be a library with your functions, compiled as a shared library, like so:
gcc -Wall -o libexample.so example.c -shared -fPIC
That being said, if you're going to the trouble of compiling a shared library like this, you'll probably just want to call the functions in your binary. You can do that if you link your library in at compile-time:
gcc -Wall -o test test.c -L. -lexample
-L.
tells the linker to look for libraries in the current directory (.
) and -lexample
tells it to link with a library named "libexample.so". If you do this, you can just call the library functions directly within your program.