I read that you can use the dynamic linker API using dlfcn.h Here's a code example using the API
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int x[2]={1,2};
int y[2]={3,4};
int z[2];
int main(){
void *handle;
void(*addvec)(int *,int *,int *,int);
char *error;
// Dynamically load shared library that contains addvec()
handle=dlopen("./libvec.so",RTLD_LAZY);
if(!handle){
fprintf(stderr,"%s\n",dlerror());
exit(1);
}
// Get a pointer to the addvec() function we just loaded
addvec=dlsym(handle,"addvec");
if((error=dlerror())!=NULL){
fprintf(stderr,"%s\n",dlerror());
exit(1);
}
// now we can call addvec() just like any other function
addvec(x,y,z,2);
printf("z=[%d %d]\n",z[0],z[1]);
// unload the shared library
if(dlclose(handle)<0){
fprintf(stderr,"%s\n",dlerror());
exit(1);
}
return 0;
}
it loads and links the libvec.so shared library at runtime. But can someone explain when and how linking and loading .so's(DLL's on windows) at runtime is better and more useful instead at load time? Because looking from the example it doesnt seem very useful. Thanks.