How to Create and Compile a Static Library in Linux (2024)

Brief: This article guide provides an understanding between static and dynamic libraries and thereafter demonstrates how a user can create a static library in Linux via the aid of the Linux ar command.

During the compilation process of a C program, an object code is usually the end result of a successful compiler runtime. Afterward, a linker is invoked to make the library function code available to a user program. The linker accomplishes this objective either by making the library function code copy available to the user object code or by availing the library function code at run-time.

When the linker creates a copy of these re-usable library function codes and passes/avails them to an executable program file, a static library is born. It’s called a static library because the libraries and/or library files are statically linked. Static libraries in Linux are identified by the '.a' file extension.

Features of a Static Library

Before we create a static library in Linux, we should note the following advantageous features:

  • Reduced Size – They are smaller in size in comparison to shared libraries hence advantageous to limited storage space systems.
  • Improved Performance – During runtime, shared libraries are associated with the overhead of loading (tracing a shared library location, verifying its version, and mapping it to memory for an executable program to access it). With the static library, all the necessary code and data are readily availed to the executable program.
  • Improved Portability – Static libraries’ linked executables are easy to deploy and run since they do not depend on external runtime environments or libraries. They are therefore adaptable to different systems, unlike shared libraries.
  • Improved Stability – The executable program’s stability is likely improved since it is bundled with the static libraries which prevent the library from being modified or updated while on a different system environment (a key cause for compatibility issues).

Creating a Static Library in Linux

We will accomplish the creation of our static library by covering the following steps:

Step 1: Create a C File

The first step is to create a C file that will accommodate all the needed library functions.

$ nano mylibrary.cOR$ vi mylibrary.c

We will use the following code for simplicity reasons:

/* Filename: mylibrary.c */#include <stdio.h>void task(void){printf("task() called from a static library");}

Step 2: Create a Library Header File

The next step is to create the library header file:

$ nano mylibrary.hOR$ vi mylibrary.h

The code to use is:

/* Filename: mylibrary.h */void task(void);

Step 3: Create an Object File

The next step is to compile the above library files and create an object file mylibrary.o using a gcc compiler.

$ gcc -c mylibrary.c -o mylibrary.o
How to Create and Compile a Static Library in Linux (1)

The -c flag compiles the C library and the -o flag creates the library object. You can create multiple library objects from different C files.

Step 4: Create a Static Library

Once you have the needed number of library objects, you can proceed to create a static library. Here, we will borrow the functionality of the Linux ar Command.

$ ar rcs mylibrary.a mylibrary.o

The above command creates a static library called mylibrary.a. You can also include multiple library objects in the following command format:

$ ar rcs mylibrary.a lib1.o lib2.o lib3.o … 
How to Create and Compile a Static Library in Linux (2)

The r option creates an archive of the provided library object files, c option initiates the archiving process and s option creates the archive’s index (symbol table).

The created static library file (mylibrary.a) is now portable and ready for use.

How to Use Static Library in Linux

To demonstrate the usage of this static library, let us create a driver program with the help of a C file.

$ nano driver.cOr$ vi driver.c

Add the main function using the following code:

/* filename: driver.c */#include "mylibrary.h"void main(){task();}

Create the library object from this C file:

$ gcc -c driver.c -o driver.o
How to Create and Compile a Static Library in Linux (3)

We will now use the generated library object to create a driver program and link it to our static library.

$ gcc -o driver driver.o -L. -l:mylibrary.a

The -L. point to the location of the static library i.e current folder and -l:mylibrary.a creates a static link between the static library and the driver program.

We can now test the execution of this driver program:

$ ./driver
How to Create and Compile a Static Library in Linux (4)

The output “task() called from a static library” originating from the C file we created earlier confirms that the driver program and the static library are statically linked.

Modifying Static C Libraries

In reference to the above-covered steps that led to the creation of a static library (mylibrary.a), we can conclude that the creation of a static library only requires the existence of valid object files (library objects). Therefore, we can redefine a static library as a composition of library objects.

Viewing the Content of a Static Library

Suppose, we want to display all the library objects that make up our static library, we will use the ar command:

$ ar t mylibrary.aor$ ar tv mylibrary.a 
How to Create and Compile a Static Library in Linux (5)

The -t command option lists all the object files present and -v is for verbose display and provides a detailed preview that includes file attributes like owner, group, timestamp, and permission.

Extracting Library Object from Static Library

If you need to extract and inspect a library object from a static library, utilize the ar command option x. We can also combine the command with the verbose option (v) for the interactive execution of the command.

The following command extracts all available library objects.

$ ar xv mylibrary.a

The following command extracts a single specified library object.

$ ar xv mylibrary.a mylibrary.o 

The following command extracts multiple specified library objects.

$ ar xv mylibrary.a lib1.o lib2.o lib3.o

Adding Library Object to Static Library

Supposing the static library mylibrary.a needs to accommodate additional library objects, we will make use of the ar command option r. We can even combine it with the verbose option.

This command adds a single specified library object to the static library

$ ar rv mylibrary.a mylibrary.o 

This command adds multiple specified library objects to the static library.

$ ar rv mylibrary.a lib1.o lib2.o lib3.o

Afterward, view the content of the static library to confirm the addition of the selected library objects.

$ ar tv mylibrary.a 

Deleting Library Objects from Static Library

If you want to delete single or multiple library objects from a static library, make use of the ar command option d. Combine it with the verbose option to see the library object files being deleted.

This command deletes a single specified library object from the static library

$ ar dv mylibrary.a mylibrary.o 

This command deletes multiple specified library objects from the static library.

$ ar dv mylibrary.a lib1.o lib2.o lib3.o
Conclude

A major advantage associated with static libraries is their ability to accelerate the program execution process. However, if the static library undergoes any changes, a user will have to every time recompile the main program for the changes to take effect.

That said, you can now employ the concept of static libraries in your current and future Linux projects.

How to Create and Compile a Static Library in Linux (2024)
Top Articles
Filecoin (FIL) Price Prediction 2024 2025 2026 2027 - 2030
Mastering Bar Charts: Visualize Information with Precision
Dragon Age Inquisition War Table Operations and Missions Guide
Froedtert Billing Phone Number
Frank Lloyd Wright, born 150 years ago, still fascinates
Www.politicser.com Pepperboy News
Craigslist Free Stuff Appleton Wisconsin
The Haunted Drury Hotels of San Antonio’s Riverwalk
Geometry Escape Challenge A Answer Key
Housing Intranet Unt
Planets Visible Tonight Virginia
Facebook Marketplace Charlottesville
Dump Trucks in Netherlands for sale - used and new - TrucksNL
Dignity Nfuse
Napa Autocare Locator
Nearest Walgreens Or Cvs Near Me
Ivegore Machete Mutolation
If you have a Keurig, then try these hot cocoa options
Impact-Messung für bessere Ergebnisse « impact investing magazin
Hdmovie2 Sbs
Wat is een hickmann?
Bidrl.com Visalia
Culver's.comsummerofsmiles
Watson 853 White Oval
Dr Seuss Star Bellied Sneetches Pdf
Danielle Moodie-Mills Net Worth
031515 828
DIY Building Plans for a Picnic Table
Rubmaps H
Kagtwt
Exploring TrippleThePotatoes: A Popular Game - Unblocked Hub
El agente nocturno, actores y personajes: quién es quién en la serie de Netflix The Night Agent | MAG | EL COMERCIO PERÚ
2012 Street Glide Blue Book Value
Iban's staff
Federal Student Aid
Police Academy Butler Tech
Tmka-19829
The Blackening Showtimes Near Regal Edwards Santa Maria & Rpx
Bbc Gahuzamiryango Live
Why I’m Joining Flipboard
manhattan cars & trucks - by owner - craigslist
Yakini Q Sj Photos
What Is The Optavia Diet—And How Does It Work?
Best Haircut Shop Near Me
Pixel Gun 3D Unblocked Games
20 Mr. Miyagi Inspirational Quotes For Wisdom
Join MileSplit to get access to the latest news, films, and events!
Westport gun shops close after confusion over governor's 'essential' business list
Brutus Bites Back Answer Key
Strawberry Lake Nd Cabins For Sale
Where Is Darla-Jean Stanton Now
BYU Football: Instant Observations From Blowout Win At Wyoming
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated:

Views: 5519

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.