Static and Dynamic libraries

Hugo Bayona
2 min readDec 17, 2019

--

What are libraries?

In simple words, a library is a compiled code that can be reused by other programs.

Static libraries

These libraries are pieces of code that are included in the binary at the moment you compile your code, therefor every compiled program has a copy of that compiled code.

Dynamic libraries

On the other hand, dynamic libraries exist outside the binary, which means that all the programs calling this library are only using one copy of that compiled code.

How to make Static libraries (Linux)

In this case, we are going to use the C language.

First, write your library

$ ls
my_lib.c

Add the prototype to the header file

$ ls
my_lib.c header.h
$ cat header.h
#ifndef HEADER_H
#define HEADER_H
int _putchar(char c);
#endif

Compile keeping the *.o files

$ gcc -Wall -Werror -Wextra -pedantic -c *.c
$ ls
my_lib.c header.h my_lib.o

Now, build your static library with ar

$ ar -rc libr.a *.o
$ ls
my_lib.c header.h my_lib.o libr.a

In this case, we use only one .c file, but this is usually done with many *.c files, so when you finish you have a static reference for all your codes.

$ gcc -Wall -Werror -Wextra -pedantic main.c libr.a

How to make Dynamic libraries (Linux)

First, write your library

$ ls
my_lib.c

Add the prototype to the header file

$ ls
my_lib.c header.h
$ cat header.h
#ifndef HEADER_H
#define HEADER_H
int _putchar(char c);
#endif

Compile keeping the *.o files and use the flag -fPIC. This will make that our *.o files don't get a fixed address… so it becomes Dynamic

$ gcc -Wall -fPIC -c *.c
$ ls
my_lib.c header.h my_lib.o

After this, you need to compile your dynamic library

$ gcc -shared -o liball.so *.o
$ ls
my_lib.c header.h my_lib.o liball.so

Add the path of your dynamic library to your environment.

You are going to create a .conf file

$ sudo vim/etc/ld.so.conf.d/myLibs.conf

Add the full PATH of your lib (only the PATH, not the name of the file)

/home/user/slibra

And finally, tell the system these libraries exist

$ sudo ldconfig

Differences

Dynamic or Static, both are good and bad, they el depends on your necessities for the problem you are working on.

This is a table from geeksforgeeks that summarise the difference between them it’s up to you how and when do you use each one.

https://www.geeksforgeeks.org/difference-between-static-and-shared-libraries/

--

--

Hugo Bayona
Hugo Bayona

Written by Hugo Bayona

Pentester | Software Developer

No responses yet