Create Statically linked libraries

cpplibraries
Table of contents
  • Create Statically linked libraries
  • Compiling and linking dynamic libraries

Create Statically linked libraries

To start with, let's create a basic library that we will then be able to consume from other programs.

cpp
#include <iostream>
void hello() {
std::cout << "Hello World from the library!" << std::endl;
}

you need to type the following command:

sh
$ clang -c hello.cpp

The flag -c tells clang to output an object file. After the flag, we state which cpp file to use when building the object file. This command will produce the file hello.o

we use the following command to generate an .a file:

sh
$ ar rvs mylib.a hello.o

We can now consume our newly created library in other projects. Let's create a very simple program that will use our library saved the file as main.cpp:

cpp
void hello();
int main() {
hello();
}

This program will call the hello unction which the compiler we then look for an implementation in our linked libraries. Compile the program and link our static library with the following command:

sh
$ clang main.cpp mylib.a -o main

Compiling and linking dynamic libraries

Following are the step for compiling and linking dynamic libraries:

The hello.cpp file now look like:

cpp
#include <iostream>
__attribute__((visibility("default")))
void hello() {
std::cout << "Hello World from the dynamic library!" << std::endl;
}

We can create a .dylib from the terminal shell with the following command:

sh
$ clang -dynamiclib -o mylib.dylib hello.cpp

Next, we can link and build our program with our newly created library exactly like the previous example with the following commands:

sh
$ clang main.cpp mylib.dylib -o main

One of the bonuses is the fact that when you make changes to a dynamically linked library, you do not have to recompile the entire program; we only have to recompile the library. To see this in action, let's make a small change to the hello.cpp

cpp
#include <iostream>
__attribute__((visibility("default")))
void hello() {
std::cout << "Hello World from the dynamic library!" << std::endl;
std::cout << "Version 2" << std::endl;
}

Next, we can recompile our library with the same command as before:

sh
$ clang -dynamiclib -o mylib.dylib hello.cpp

This makes upgrading very easy, but can also quickly lead dll mismatching on machines without the updated library, often referred to as Dll Hell.

The art of knowing is knowing what to ignore - Rumi