Source:

Jacob Sorber

https://www.youtube.com/watch?v=_kIa4D7kQ8I&list=PL9IEJIKnBJjFn6zQQkJ2e8vxCVxhl2yuD&index=2

Dynamic Loading

When we don’t know what functions we are using, we can use dynamic loading. Without recompiling the code we can load libraries dynamically during runtime.

Functions used are (linux, Mac):

Functions used are (Windows ):

Exmaple Code:

//libplus1.c

char *get_library_name()
{
	return "I add 1 to ints";
}

int do_operation(int i)
{
	return i + 1;
}
//libplus2.c

char *get_library_name()
{
	return "I add 2 to ints";
}

int do_operation(int i)
{
	return i + 2;
}
//test.c

int main(int argc, char **argv)
{
	if (argc < 3)
	{
		printf("usage: %s <library> <number>\\n", argv[0]);
		exit(1);
	}
	
	char *librarypath = argv[1];
	int the number = atoi(argv[2]);
	
	//RTLD_LAZY - use lazy loading, functions loads when the function gets used
	void *libhandle - dlopen(librarypath, RTLD_LAZY);

	int (*opfunc) (int);
	// Get address of "do_oepration"
	opfunc = dlsym(libhandle, "do_operation");
	
	printf("%d --> %d\\n", thenumber, opfunc(thenumber));
	
	dlclose(libhandle);
}

Makefile