Create c++ static library in Linux
In this blog we are going to make static c++ library which can be used to share c++ code among other c++ programs and distribute the code with other developers. We will write simple c++ calculator class and package it into static library in Linux.
Lets create simple c++ calculator class and its header file
// Calculator.hpp#ifndef CALCULATOR_HPP#define CALCULATOR_HPPclass 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 its time to create the static library. To create static library we will use linux archive tool which will archive our object file into static library.
ar -rcs libcalculator.a Calculator.o
The above command will create the static library which can we used in other programs.
The Naming convention used in Linux for static library is the name starts with lib and 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).
Now you can put Calculator.h file in /usr/local/include where g++ looks for header file. And put libcalculator.a file in /usr/local/lib directory where g++ looks for library.
Here’s is simple example which is using 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 .