C static libraries

A library is where we can keep items that we might call later for our program, which will actually save us a lot of time.

But what is a static library in C?

Is a compiled file which contains the symbols that the main program needs to operate, such as functions and variables.

When we call a function in the main, the compiler will link that code wrote in main with the code of the function that is in the library, and it will be added.

Theres another type of library in C called dynamic library:

The process of compilation is still the same of the static libraries until it gets to the linker, add that point it will be added not the code of the function you called but the address where the function is located in the library.

But why should we use them?

Libraries provide you with many useful functions that will save you time by using them instead of waste time trying to create them.

How to create a static library in Unix? How it works?

  1. Compile and assembly your .c file with the command: “gcc -c *.c” (with the “-c” flag we make sure it compiles and assemble but not link) and will create the “.o” extension file which mean object code.

Example:

Example_file.c Hello_world.c

gcc -c *.c

ls

Example_file.c Example_file.o Hello_world.c Hello_world.o

2. Then we use the command “ar” which means archiver to create a static library adding an “rc” which stands for “replace” older objects with the new one and “create” library if it doesnt exist.

Example:

ar rc Example_library.a Example_file.o Hello_world.o

or

ar rc Example_library.a *.o

This command creates a static library called Example_library.a and puts copies of the object files Example_file.o, Hello_world.o in it. As you can see in the last line we used the “*.o” command which means it will copy all the files ending with “.o”.

But how do we use libraries?

After we create (modified) them, we just need to index it by the “ranlib” command.

Example:

ranlib Example_library.a

--

--

--

Holberton Student #Cohort14

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Instruments for data scientist toolbox

Python variable Types:

The Path to Awesomeness at Comparethemarket.com

Extracting Data From Passports With A.I (No Coding!)

Introduction to creating a Sinatra and Active Record.

📢News of the Week

Basic Things to know before starting embedded systems.

The Service Mesh Mystery

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
Daniel Ortega Chaux

Daniel Ortega Chaux

Holberton Student #Cohort14

More from Medium

Install and Setup Git On Windows.

Git official logo

Plotting real-time graph from Bluetooth device using C#

Fixing my BF1942 woes with Win32 APIs

Wazaterm Features