Difference between Static and Dynamic Libraries

Cody Paral
2 min readApr 17, 2018

--

The reason we use libraries in general is because it is an accumulation of common functions that a programmer created and use’s often. It allows them to have access to all their files by including them into a program at time of compilation. How ever static and dynamic libraries include this information in different ways.

Dynamic libraries include the address of the library instead of including the actual code in the library. Dynamic linking links at run time, instead of at compilation. This allows functions to have a special place in memory, allowing each program to be able to access them without using multiple copies. Static libraries are compiled with the program and are part of the program. No other program can access the library.

To create a dynamic library in C using linux use the following command:

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

gcc: This is a c compiler
-g: Includes Debugging information
-fPIC: “Positin Independent Code” This flag allows the
code to be located at any virtual address.
-Wall: Includes all flags for gcc
-Werror: Makes any Warning Errors
-Wextra: Includes extra flags
-pedantic: ensures the standard of C is the same.
*.c: Tells the computer to use all the .c files
-shared: creates the shared library
-o: allows you to name the output
liball.so: name of the output file.

To use the dynamic library include it during your compilation stage

$ gcc -Wall -Werror -Wextra -pedantic FILE1.c liball.so -o FILENAME

To create a static library in C using Linux use the following command:

$ ar -rc *.o liball.a

ar: allows you to create, modify, and extract from archives
-r: flag that inserts the file members into the archive
-c flag that creates the archive
*.o: tells the computer to use all the .o files in directory

To use the static library include it during your compilation stage

$ gcc -g FILE1.o liball.a -o FILENAME

How do static and dynamic libraries differ?

A static library is linked into the program, it is a compilation of .o files added into the program during the compilation process. Dynamic libraries are separate from the program, they are compiled, linked and installed separately from the program. So any program can make calls to it.

What are the drawbacks to each of them?

Static libraries are compiled with the program, which means updating the library means you would have to recompile the whole program. However no outside program can access that which might be better for security.

Dynamic libraries have one big downside, that is if multiple programs are using the same library, and each program is expecting different versions of the library there will be big problems. To avoid that the library must be updated keeping the library backwards compatible.

--

--