Why you should use libraries (when programming)

Nick Arshadi
2 min readMay 5, 2020

--

Libraries are a great invention and one of my favorite places. They are quiet, and you can find any information you want. I study more efficiently when I am in a library.
But this blog post is about libraries in UNIX/LINUX.

First of all, what is a library?

A library allows you to store all your functions inside them. When using them, your system finds them significantly faster than if it would search them otherwise.

First of all, it's important to differentiate the two types of libraries that exist.
There are static libraries and dynamic(some prefer saying “shared”) libraries.

I explain their differences in the following part of my blog.

How do I create libraries?

This blog is dedicated only to libraries in Linux.

To create a static library with the name “libutil.a” including all your c-files you type the following 3 commands:

gcc -fPIC -c *.c
ar rc libutil *.o
ranlib libutil.a

We use the GNU C Compiler and ar.
The first line converted the c-files to machine code, excluding the linking process. The second line does create the library, and the third line does index the library.

Now let us create a dynamic library which we name “libutil”:

gcc -fPIC -c *.c
gcc -shared -o libutil.so *.o

Et Voila that is it you have successfully created a shared library.

What are the differences between both library types?

This question is simple to answer. When you compile a c file, it encounters 5 compilation steps. The last stage is called “linker.”

Static libraries get integrated into your final compiled file during the linking process. Therefore if you compile 6 files that include your library you integrate the source code of your library in 6 files. There fore wasting memory space because you have implemented the same code n times.

Dynamic library’s on the other hand, don’t get fully integrated into your compiled file (in windows systems that is the .exe file).

Dynamic library’s run through two steps.
1. During the linking process, you store pointers to the actual library inside your compiled file.
2. And the second step is that when a program executes, the library gets loaded into the memory. This may sound like a drawback in speed. But if you compare both library types, the execution speed does not vary significantly.

I hope I was able to inform you sufficiently on this topic, and I hope you have a great day.
And keep coding :)

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

--

--

Nick Arshadi
Nick Arshadi

No responses yet

Write a response