Create c++ static library in Linux

The murky waters of cpp

In this blog, we are going to make a static c++ library that can be used to share c++ code among other c++ programs and distribute the code with other developers. We will write a simple c++ calculator class and package it into the static library in Linux. Lets create simple c++ calculator class and its header file.

// Calculator.hpp
#ifndef CALCULATOR_HPP
#define CALCULATOR_HPP
class Calculator {
  public:
  double sum(double firstNumber, double secondNumber);
  double multiply(double firstNumber, double secondNumber);
  double substrct(double firstNumber, double secondNumber);
  double divide(double dividend, double divisor);
};
#endif
// Calculator.cpp
#include “Calculator.hpp”

double Calculator::sum(double firstNumber, double secondNumber) {
  return firstNumber + secondNumber;
}
double Calculator::multiply(double firstNumber, double secondNumber) {
  return firstNumber * secondNumber;
}
double Calculator::substrct(double firstNumber, double secondNumber) {
  return firstNumber— secondNumber;
}
double divide(double dividend, double divisor) {
  return dividend / divisor;
}

Now we have our source code lets compile the code into object code using g++ g++ -c Calculator.cpp

After running the above command you will get Calculator.o Now it's time to create the static library. To create a static library we will use Linux archive tool which will archive our object file into a static library.

ar -rcs libcalculator.a Calculator.o

The above command will create the static library which can be used in other programs.

The Naming convention used in Linux for the static library is the name starts with lib and the static library has .a extension. i.e., every static name should look something like lib[whatever].a . use -l flag to link the library while compiling code. In our case -lcalculator (library name without lib and .a extension).

Here’s is a simple example which is using the above library.

// main.cpp
#include <iostream>
 // Our header file in /usr/local/include
#include “Calculator.hpp”

int main(int argc, char
  const * argv[]) {
  Calculator c = Calculator();
  std::cout << “sum: “ << c.sum(10, 10) << std::endl;
  return 0;
}

Compile the above code with -lcalculator flag.

g++ main.cpp -lcalculator

Run the a.out file and you can see our library code is working.