Shared (dynamic) libraries in the C programming language

Jimmy Thong
meatandmachines
Published in
2 min readJan 14, 2017

Libraries are linked in the final step of C program compilation (where a C program is converted to a form the machine can execute). There are two ways libraries can be linked: statically and dynamically, turning them into either a static library, or a dynamic (shared) library respectively.

Static libraries are the first type of library to be provided on UNIX systems. They’re usually faster than shared libraries because a set of commonly used object files is put into a single library executable file. One can build multiple executables without the need to recompile the file. Because it’s a single (static library) file to be built, the link commands are simpler than shared library link commands, as you simply specify the name of the static library (as opposed to listing a long series of object files).

To create a static library (Linux only) [the “all” in “liball.so” an arbitrary name, more about this below]:

$ ar -rc liball.a *.o

The -r flag inserts the file members into the archive [liball.a].

The -c flag creates the archive [liball.a].

The *.o command acts upon all files with with the suffix .o [object files]

To use a static library (Linux only):

gcc -g -o prog prog.o liball.a

The main drawbacks are static libraries are larger than shared libraries (all the object files are built into that single executable file). Also, if any changes have to be made to the static library, it has to be recompiled and relinked.

Shared (dynamic) libraries are linked dynamically simply includes the address of the library (whereas static linking is a waste of space). Dynamic linking links at the run-time, not the compilation time. Thusly, all the functions are in a special place in memory space, and every program can access them, without having multiple copies of them.

To create the shared library (Linux only), you can use the following command two command lines:

gcc -g -fPIC -Wall -Werror -Wextra -pedantic *.c -shared -o liball.so

The -g flag includes debugging information in the compiled program.

The -fPIC flag stands for “Position Independent Code” generation, a requirement for shared libraries. Because it’s impossible to know where the shared library code will be, this flag allows the code to be located at any virtual address at runtime.

The -shared flag creates the shared library (shared libraries have the prefix lib and suffix .so [for shared object].

To use a dynamic library (Linux only):

gcc -g -wall -o prog prog.c liball.so

Reference:

--

--

Jimmy Thong
meatandmachines

Makerspace Teacher, Code Coach, Amateur Home Cook, Writer