How to Create a Static Library in C++?
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
C++
// mylibrary.h #ifndef MYLIBRARY_H #define MYLIBRARY_H void sayHello(); int addNumbers( int a, int b); #endif // 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
C++
// mylibrary.cpp #include "myLibrary.h" #include <iostream> using namespace std; // function 1 void sayHello() { cout << "Hello from the static library!\n" ; } // function 2 int addNumbers( int a, int b) { return a + b; } |
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:
C++
// main.cpp #include "mylibrary.h" using namespace std; int main() { // calling sayHello() function sayHello(); // calling addNumbers function and storing the result int result = addNumbers(5, 7); cout << "The result is: " << result << "\n" ; return 0; } |
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