Open In App

How to Create a Static Library in C++?

Last Updated : 15 Feb, 2024
Comments
Improve
Suggest changes
4 Likes
Like
Report

C++ allows users to add their own libraries to reduce the amount of code we have to write in our program. A static library in C++ is a library that is linked to the program at compile-time. In this article, we will learn how to create a static library in C++ from scratch.

Create Static Library in C++

To create a static library in G++ compiler, follow the below steps:

1. Create Library Source Code and Header Files

Open your preferred text editor or integrated development environment (IDE), and create a new header file with the .h extension. Here we will declare the functions that we want to include in the library.

Header File: mylibrary.h

This header file allows other programs to access the functions in your static library.

Now create a source file with .cpp extension and define the functions that were declared in the header file.

Source Code File: mylibrary.cpp

2. Compile the Library Source Code to an Object File

Open a terminal in the directory containing mylibrary.cpp and run the following command:

g++ -c mylibrary.cpp -o mylibrary.o

This command generates an object file (mylibrary.o) from the source code.

3. Create the Static Library

Use the ar (archive) tool to create a static library named libmylibrary.a from the object file mylibrary.o. Run the following command:

ar rcs libmylibrary.a mylibrary.o

This command creates the static library, and its is now ready to use in our program.

4. Write a Main Program that Uses the Static Library

Create a new file named main.cpp that uses the functions from the static library.

main.cpp:

5. Compile the Main Program with Static Library

Compile the main.cpp file and link it with the static library for this run the following command:

g++ main.cpp -L. -lmylibrary -o myprogram

This command links the main.cpp file with your static library (-lmylibrary) and produces an executable named myprogram.

6. Run the Program

Run the compiled program.

./myprogram

Expected Output

Hello from the static library!
The result is: 12

Next Article
Practice Tags :

Similar Reads