![]() |
VOOZH | about |
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.
To create a static library in G++ compiler, follow the below steps:
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
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.
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.
Create a new file named main.cpp that uses the functions from the static library.
main.cpp:
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.
Run the compiled program.
./myprogram
Expected Output
Hello from the static library!
The result is: 12