Creating and Using Own Static or Dynamic Library in C++ On Linux Platform

This post is dedicated to create own static c++ library and link it with your own project. For demonstration purpose we write function for adding two integer. We will create library from this function. We will write first code of source file and header file. 

add.h
#pragma once
namespace ownLib {
int sum( int a, int b );
}
add.cpp 
namespace ownLib {
int sum( int a, int b ) { 
    return a + b;
}
}
Now our job is to create a library using these 2 files. After creating library  we can functions from our library in any other projects by just linking the path of library.
We will write code for our main project now and we will use add function from our self created library.

Main.cpp
#include <stdio.h>
#include "add.h"

int main() {
    int a = 5;
    int b = 8;
    int c = ownLib::sum( a, b );

    printf( "sum of %d and %d is %d\n", a, b, c );

    return 0;
}

We will use cmake to create library and link with main source file. 

CMakeLists.txt

# CMake instructions to make the static lib
cmake_minimum_required(VERSION 3.2)

include_directories(src)
ADD_LIBRARY( MyLib SHARED
             src/add.cpp )

# Replace SHARED by STATIC for static library, 
ADD_EXECUTABLE( ${EXE}
                Main.cpp ) 

TARGET_LINK_LIBRARIES( ${EXE}
                       MyLib )
Create build directory for output of CMake  and src directory to keep source file of library. My directory structure is as below:
.
├── build
├── CMakeLists.txt
├── Main.cpp
└── src
    ├── add.cpp
    └── add.h


Now change working directory to build and run following command in terminal: 

$ cmake ..
$ make 

You will get the final executable Test in build folder. To check the output run following in terminal

$ ./Test

output will be 

sum of 5 and 8 is 13.

That's all for the scope of this post. We used add function from self compiled library in our project. If you want link library dynamically instead of statically replace STATIC in CMakeLists.txt file with SHARED.
Demo:

If you are windows user then go through Microsoft's official post

No comments:

Post a Comment

Rendering 3D maps on the web using opesource javascript library Cesium

This is a simple 3D viewer using the Cesium javascript library. The example code can be found here . Click on question-mark symbol on upp...