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.cpp#pragma once namespace ownLib { int sum( int a, int b ); }
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.
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