Static vs Dynamic libraries
Static libraries are loaded into an application compile time. They increase the size of the application executable. Static libraries use extensions:
- Windows:
.lib
or.a
- UNIX based: filename starts with a lib, and ends with .a (archive)
- Windows:
Dynamic libraries are loaded into an application runtime. The size of the application executable is not impacted in this case. Dynamic libraries use extensions:
- Windows:
.dll
- UNIX based:
.so
(shared object) or.dylib
- Windows:
Why should you create a static library?
With static libraries, application gets contained in a single executable file. This simplifies distribution and installation.
If some functions are being called from many places and are not frequently modified, it is best to put them together in a library to speed up the compilation of the program. What is in the linked library is not re-compiled, saving time.
How to build a static library?
Requirements
- g++, a GNU C++ Compiler .
To check if g++ is present on your system run -
on command prompt.g++ --version
If you do not have g++ on your system, follow this link .
Step 1 - Create source and header files
library.hpp
#include <iostream>
using namespace std;
void printSquare(const int& i);
library.cpp
#include "library.hpp"
void printSquare(const int& i) {
cout << "Square : " << i*i << endl;
}
Step 2 - Build your library
g++ -c library.cpp -o library.o
ar rcs library.a library.o
In the above command -
ar
is the archiverr
stand for 'replace or update old files in the library'c
tells the program to create a librarys
means 'sort' the library, so that it will be indexed and access to library functions will be faster
Congratulations! You've successfully created a static library.
You can find this library.a file in your current directory -
How to use this static library?
Let us create a small application in the same directory -
main.cpp
extern void printSquare(const int& i);
int main() {
printSquare(9);
return 0;
}
The extern
keyword specifies that the symbol has external linkage (is defined elsewhere). For multiple function declarations in a block extern "C"
modifier can be used.
Compile this main application -
g++ -c main.cpp -o main.o
Now, build the executable -
g++ -o main main.o -L. library.a
Here -
L
stands for “look for library files”.
(the dot after ‘L’) is for the current working directory
Run the main executable created in this directory -
C:\example> main
Square : 81
There you go! The linked library worked alright.
Start using static libraries for rarely modified code in your application that is being called in multiple places and enjoy the speed boost in building your application!