C Static Libraries: how do they work?

© Luuk Kramer

Introduction

A static library, also known as a statically-linked list, is simply a common space used to store object files. Once created they allow the user to be able to link programs with each other without requiring recompilation. They also allow 3rd party linking without having to give out the library source code. A purported plus is a slight increase in overall speed as the compilation skipped sheds a bit of processing load, this however is negligible with today’s faster compilers and is more of a footnote of why they were used in the past.

Static libraries work by indexing the object files that are passed to it. In simple terms it neatly stores all the .o files that are passed to it. This way, upon the linking stage of compilation, our compiler doesn’t have to scramble around searching for the necessary functions in memory, instead they are all stored in a single .a file and are readily accessible at runtime. It is not necessary to name your static library files with a .a extension, but programmers enjoy their conventions and will look at you funny if you stray from the path.

To create a static library

We must first ensure that we have our functions properly created in their own .c files. Once we’re sure we have everything we need we can move on to compiling. A simple

$ gcc -c <filename.c>

command will compile our file into an object file output. Now it’s ready to be added to a library! We call upon our archiver with the command:

$ ar -rc <libraryname.a> <filename.o>

A final step is to ensure that our files are properly indexed after being added to our library is by running:

$ ranlib <libraryname.a>

And just like that we have created and sorted our library file to ensure the quickest compilation times!

Happy coding!

--

--

--

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

Recommended from Medium

Day 1: An Unending Journey

AWS EC2 Comparison: C5d vs C5n

Deploying Envoy Filter on Istio

Working with Strings in BigQuery

How to build efficient and perfomant Data Structures in BigQuery

BEYOND RESILIENCE: HELP US BRING THE OS and LIMINAL LAB into a FUTURE of POSSIBILITY

How to Start with Container Security?

Reverse engineering of esp32 flash dumps with ghidra or IDA Pro

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
Gabriel Vazquez

Gabriel Vazquez

More from Medium

CS373 Spring 2022: Vijay Kiran Vuyyuru

Getting Started With ESP32 & Arduino IDE: Simple I/O

C Static Libraries and gcc

Nexus Installation In Linux Centos