Creating and Using Dynamic Libraries ( C )

jgra007
3 min readSep 15, 2020

Why use Dynamic library: or shared library is a collection of functions compiled and stored in an executable with purpose of being linked by other programs at run-time. Dynamic libraries provide a means to use code that can be loaded anywhere in the memory. Using this the size of code is lower that if we use a lot of code coping and pasting code.

How to create a dynamic library

First we need to create de object files with the command gcc -fPIC -c *.c for all the .c files in the current directory.

The -fPIC is a flag that stands for position independent code, required by dynamic libraries.

Now we are going to create the library name with the command

gcc *.o -shared -o librayname.so to all the object files

The -shared key tells the compiler to produce a shared object which can then be linked with other objects to form an executable.

Now we have a library that is ready to use.

How to use a dynamic library:

The porpose of the dynamic libraries is to be shared dinamically during the linking with other programs, and tomake it, we havee to add a path to our library to the LD_LIBRARY_PATH env variable

export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH

Now we can compile and execute our program.

nm libraryName.so

Differences between Dynamic and static libraries

A Static library or statically-linked library is a set of routines, external functions and variables which are resolved in a caller at compile-time and copied into a target application by a compiler, linker, or binder, producing an object file and a stand-alone executable. This executable and the process of compiling it are both known as a static build of the program. Historically, libraries could only be static.
They are usually faster than the 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 is a single file to be built, use of link commands are simpler than shared library link commands, because you specify the name of the static library.

Shared libraries are .so files.
These are linked dynamically simply including the address of the library whereas static linking is a waste of space. Dynamic linking links the libraries at the run-time. Thus, all the functions are in a special place in memory space, and every program can access them, without having multiple copies of them.

Advantages and drawbacks

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

jgra007
jgra007

No responses yet

Write a response