Creating a simple static library
This article describes how to create a simple static library using C++. A static library is a collection of object files that are linked with and copied into a target application at compile time. The resulting executable contains all the object code from the static library, so it can be executed independently of the library.
Static library
Let’s start by creating a simple square class:
1// src/square.h
2#ifndef SQUARE_H
3#define SQUARE_H
4
5class square {
6private:
7 double length;
8public:
9 square(double length);
10 double area();
11};
12
13#endif
and its corresponding implementation:
1// src/square.cpp
2#include "square.h"
3
4square::square(double length): length(length) {}
5
6double square::area() {
7 return length * length;
8}
and a simple main.cpp program to use it:
1// src/main.cpp
2#include "square.h"
3#include <iostream>
4
5using namespace std;
6
7int main() {
8 square s(5);
9 cout << "Area: " << s.area() << endl;
10
11 return 0;
12}
The following commands will compile the program in the bin directory:
1mkdir -p {obj,lib,bin}
2g++ -c --std=c++2a -o obj/square.o src/square.cpp
3ar rvs lib/libsquare.a obj/square.o
4g++ --std=c++2a -o bin/main src/main.cpp -Llib -lsquare
5bin/main
-
g++ -c --std=c++2a -o obj/square.o src/square.cpp- This command compiles the
square.cppfile using theg++compiler. -cflag tells the compiler to generate the object file (square.o) but not perform linking.--std=c++2aflag specifies that the C++ language standard to use is C++20 (also known as C++2a).- The resulting object file
square.owill be used later for linking.
- This command compiles the
-
ar rvs lib/libsquare.a obj/square.o- This command creates a static library named
libsquare.afrom thesquare.oobject file. aris the archiver utility used to create or manipulate library files.rvsare the options passed toar, where:rstands for “replace,” meaning replace or add files to the archive.vstands for “verbose,” displaying a detailed output of the archive’s contents and operations performed.sstands for “create an index,” which adds an index to the archive to speed up symbol lookup during linking.
lib/libsquare.aspecifies the name and location of the resulting library file. In Unix systems it’s standard to use thelibprefix for libraries.
- This command creates a static library named
-
g++ --std=c++2a -o bin/main src/main.cpp -Llib -lsquare- This command compiles and links the
main.cppfile to create an executable namedmain. --std=c++2aflag specifies that the C++ language standard to use is C++20.-o mainspecifies the output file name asmain.main.cppis the source file to be compiled and linked.-Llibflag tells the compiler to search for libraries in thelibdirectory.-lsquarespecifies that the linker should include thelibsquare.alibrary during the linking process.
- This command compiles and links the
