Control Static and Shared Library Building using CMake

Control Static and Shared Library Building using CMake

When developing C or C++ libraries, one common challenge is managing how the library is built and distributed. Developers often need the flexibility to provide both static (.a or .lib) and shared (.so or .dll) versions of a library, depending on the use case. CMake provides a single, standardized option, it allows developers to control whether a library is built as static or shared with minimal effort and maximum consistency across platforms. This tutorial explains how to control static and shared library building using CMake.

Let's say we have a simple CMakeLists.txt file:

cmake_minimum_required(VERSION 3.27)
project(mytest)

option(BUILD_SHARED_LIBS "Build shared library" OFF)

set(CMAKE_CXX_STANDARD 17)

add_library(${PROJECT_NAME} test.cpp)

In CMake, the variable BUILD_SHARED_LIBS provides a simple way to control whether a library is built as static or shared. When you use the add_library command without specifying a type, CMake will create a static library if BUILD_SHARED_LIBS is set to OFF, or a shared library if it is set to ON. This allows you to switch between static and shared builds without modifying the add_library command itself. By setting BUILD_SHARED_LIBS at configure time, you can maintain a single CMakeLists.txt file while easily producing either type of library, making it convenient for cross-platform projects and flexible build configurations.

Run the following command to generate the build files for a static library, which is the default:

cmake -S . -B build

To generate the build files for a shared library, use:

cmake -S . -B build -DBUILD_SHARED_LIBS=ON

After generating the build files, build the project with:

cmake --build build

This process will produce either a static library (.a or .lib) or a shared library (.so or .dll) depending on the configuration and the system, such as Linux or Windows. On Linux, the outputs are typically libmytest.a for static or libmytest.so for shared. On Windows, they are mytest.lib for static and mytest.dll for shared.

Leave a Comment

Cancel reply

Your email address will not be published.