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.
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)
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)
To build the libraries, you need to create a build directory and run CMake from there:
mkdir build
cd build
cmake ..
make
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?