How do I create static and shared libraries in CMake for C++?

In CMake, creating static and shared libraries for C++ is straightforward. Libraries allow you to modularize your code and manage dependencies efficiently. Here, we will provide a step-by-step guide to creating both types of libraries using CMake.

Creating a Static Library

A static library is a collection of object files that are linked into a program during the linking phase of compilation. To create a static library using CMake, you can use the CMakeLists.txt file as follows:

cmake_minimum_required(VERSION 3.10) # Define the project project(MyStaticLibrary) # Add the static library add_library(MyStaticLib STATIC src/my_static_lib.cpp include/my_static_lib.h ) # Specify include directories target_include_directories(MyStaticLib PUBLIC include)

Creating a Shared Library

A shared library is a dynamic library that is linked at runtime rather than at compile time. Here’s how you can create a shared library with CMake:

cmake_minimum_required(VERSION 3.10) # Define the project project(MySharedLibrary) # Add the shared library add_library(MySharedLib SHARED src/my_shared_lib.cpp include/my_shared_lib.h ) # Specify include directories target_include_directories(MySharedLib PUBLIC include)

Building with CMake

To build the libraries, you need to create a build directory and run CMake from there:

mkdir build cd build cmake .. make

CMake C++ Static Library Shared Library CMakeLists.txt Build System