Creating and using Dynamic Libraries in “C”

How to Create a Dynamic Library (Linux)

To create a dynamic library in Linux, type the following command: gcc *.c -c -fPIC and hit return. This command essentially generates one object file .o for each source file .c . The -fPIC flag ensures that the code is position-independent. This means it wouldn’t matter where the computer loads the code into memory. Some operating systems and processors need to build libraries from position-independent code so that they can decide at runtime where they want to load it into memory. The -c options just ensure that each .o file isn’t linked yet.

Let’s work with a simple example:

We have a program written in C that contains the basic functions of a calculator, a header with all the prototypes of the program functions, and an entry point knows as the main function which calls the calculator program.

* calculator - Functions calculator
* @a: first number
* @b: second number
* Return: the result of each equation
int add(int a, int b)
return (a + b);
int sub(int a, int b)
return (a - b);
int mul(int a, int b)
return (a * b);
int div(int a, int b)
return (a / b);
int mod(int a, int b)
return (a % b);
vagrant@vagrant-ubuntu-trusty-64:~/dynamic_libraries$ gcc -fPIC -c func_ops.c

vagrant@vagrant-ubuntu-trusty-64:~/dynamic_libraries$ ls func_ops.c. func_ops.o
vagrant@vagrant-ubuntu-trusty-64:~/dynamic_libraries$ gcc -shared -o 
vagrant@vagrant-ubuntu-trusty-64:~/dynamic_libraries$ ls
func_ops.c func_ops.o

How to Use a Dynamic Library (Linux)

To use a dynamic library, it is needed to export the LD_LIBRARY_PATH which tells the dynamic link loader (ld. so — this little program that starts all your applications) where to search for the dynamic shared libraries an application was linked against.

vagrant@vagrant-ubuntu-trusty-64:~/dynamic_libraries$ export LD_LIBRARY_PATH=$PWD/



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store