First static library and now a dynamic?

Cristian Bedoya Blanco
3 min readSep 7, 2020

Yes!!! How I mentioned in a past blog library in C is a collection of header files, exposed for use by other programs. The library, therefore, consists of an interface expressed in a .h file (named the “header”) and an implementation expressed in a .c file. This .c file might be precompiled or otherwise inaccessible, or it might be available to the programmer. (Note: Libraries may call functions in other libraries such as the Standard C or math libraries to do various tasks.

Dynamic Linking doesn’t require the code to be copied, it is done by just placing the name of the library in the binary file. The actual linking happens when the program is run when both the binary file and the library are in memory. It is not copied into our program when compiled. When we have our executable and we are executing it, every time the code needs something from the library, it will look for it. If we delete the library, our program will give an error that it cannot be found.

Make a Dynamic library...

Now we going to create a library with “.so” instead “.a” extension that means shared or dynamic. following the 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.

then the command gcc *.o -shared -o liball.so (substitute your desired library name with all) and hit return. The wildcard * tells the compiler to compile all the .o files into a dynamic library which is specified by the -shared flag.

Finally, we’ll need to export the path for libraries so that programs know where to look for them by executing the following command: export LD_LIBRARY_PATH=$PWD:$LD_LIBRARY_PATH

How to use it?

The purpose of making a dynamic library is to use it with other programs. You can compile your code as follows:

expo gcc -L main.c -liball -o main

In order to accomplish this, the compiler looks through the library that is specified with the -L flag for the _puts function object code. Executing main like so: ./main would give us the following output:holberton 9. Now that you know how to create and use dynamic libraries, go and conquer the world!

@crisbedbla

--

--

Cristian Bedoya Blanco

Materials Engineer and Software Developer. First that a professional i am humanistic person. I accepts and overcomes every single challenge.