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:
// src/square.h
#ifndef SQUARE_H
#define SQUARE_H
class square {
private:
double length;
public:
square(double length);
double area();
};
#endif
and its corresponding implementation:
// src/square.cpp
#include "square.h"
square::square(double length): length(length) {}
double square::area() {
return length * length;
}
and a simple main.cpp
program to use it:
// src/main.cpp
#include "square.h"
#include <iostream>
using namespace std;
int main() {
square s(5);
cout << "Area: " << s.area() << endl;
return 0;
}
The following commands will compile the program in the bin
directory:
mkdir -p {obj,lib,bin}
g++ -c --std=c++2a -o obj/square.o src/square.cpp
ar rvs lib/libsquare.a obj/square.o
g++ --std=c++2a -o bin/main src/main.cpp -Llib -lsquare
bin/main
-
g++ -c --std=c++2a -o obj/square.o src/square.cpp
- This command compiles the
square.cpp
file using theg++
compiler. -c
flag tells the compiler to generate the object file (square.o
) but not perform linking.--std=c++2a
flag specifies that the C++ language standard to use is C++20 (also known as C++2a).- The resulting object file
square.o
will 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.a
from thesquare.o
object file. ar
is the archiver utility used to create or manipulate library files.rvs
are the options passed toar
, where:r
stands for “replace,” meaning replace or add files to the archive.v
stands for “verbose,” displaying a detailed output of the archive’s contents and operations performed.s
stands for “create an index,” which adds an index to the archive to speed up symbol lookup during linking.
lib/libsquare.a
specifies the name and location of the resulting library file. In Unix systems it’s standard to use thelib
prefix 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.cpp
file to create an executable namedmain
. --std=c++2a
flag specifies that the C++ language standard to use is C++20.-o main
specifies the output file name asmain
.main.cpp
is the source file to be compiled and linked.-Llib
flag tells the compiler to search for libraries in thelib
directory.-lsquare
specifies that the linker should include thelibsquare.a
library during the linking process.
- This command compiles and links the