In this post, I’ll guide you through the process of creating your own static C++ library on a Linux platform and linking it to your project. As a hands-on example, we’ll implement a simple function that adds two integers, then package it as a reusable library. The tutorial will begin with writing the source and header files, and walk you step-by-step through compiling, archiving, and integrating your custom library into a C++ project. We will write first code of source file and header file.
add.cpp#pragma once namespace ownLib { int sum( int a, int b ); }
namespace ownLib { int sum( int a, int b ) { return a + b; } }
Now, our task is to create a library using these two files. Once the library is created, we can use its functions in any other project simply by linking to the library’s path. Next, we’ll write the code for our main project and demonstrate how to use the add function from our custom 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:
Demo:
If you are windows user then go through Microsoft's official post
No comments:
Post a Comment