Shared libraries are “shared” in two different ways. First, in any given file system, there is exactly one .so file for a particular library. The code and data in this .so file are shared by all of the executable object files that reference the library, as opposed to the contents of static libraries, which are copied and embedded in the executables that reference them. Second, a single copy of the .text section of a shared library in memory can be shared by different running processes.
The dynamic linker loads and links shared libraries when an application is loaded, just before it executes. However, it is also possible for an application to request the dynamic linker to load and link arbitrary shared libraries while the application is running, without having to linked the applications against those libraries at compile time.
Linux and Solaris systems provide a simple interface to the dynamic linker that allows application programs to load and link shared libraries at run time. An application program that dynamically loads and links the shared library libvector.so is presented below.
#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 the shared library that contains addvec()
handle = dlopen("./libvector.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) { // Returns: NULL if previous call was OK
fprintf(stderr, "%s\n", error);
exit(1);
}
// Now we can call addvec() it 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) { // Returns: 0 if OK, -1 on error
fprintf(stderr, "%s\n", dlerror());
exit(1);
}
return 0;
}
Source:
Randal E. Bryant, David R. O'Hallaron(2011). COMPUTER SYSTEMS A Programmer's Perspective (Second Edition).Beijing: China Machine Press.