Loading and Linking Shared Libraries form Applications

Example of usage

/*addvec.c*/

int addcnt = 0;

void addvec(int *x, int *y, int *z, int n){
	 int i;
	 addcnt++;
	 for(i = 0; i < n; i++)
		 z[i] = x[i] + y[i];
}
/*multvec.c*/

int multcnt = 0;

int multvec(int *x, int *y, int *z, int n){
	int i;
	multcnt++;
	for(i = 0; i < n; i++)
		z[i] = x[i] * y[i];
}
linux> gcc -shared -fpic -o libvector.so addvec.c mulvec.c
/*dil.c*/
#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);
	char *error;
	
	handle = dlopen("./libvector.so", RTDL_LAZY);
	if(!handle){
		fprintf(stderr, "%s\n", dlerror());
		exit(1);
	}
	
	addvec = dlsym(handle, "addvec");
	if((error = dlerror()) != NULL){
		fprintf(stderr, "%s\n", dlerror());
		exit(1);
	}
	
	addvec(x, y, z, 2);
	printf("z = [%d %d]\n", z[0], z[1]);
	
	if(dlclose(handle) < 0){
		fprintf(stderr, "%s\n", dlerror());
		exit(1);
	}
	return 0;
}
linux> gcc -rdynamic -o prog2e dill.c -ldl

NOTE: the shared object module, .so file might itself have some symbol resolutions left to do. It can do it in 2 ways, first from other dynamic libararies opened with dlopen() with flag RTLD_GLOBAL and another is if the current executable is compiled with -rdynamic flag then it's global symbols are also avaiable for it's symbol resolution.

Powered by Forestry.md