CMake Configuration for Dynamically Linking spdlog

Compiling spdlog in header-only form greatly increases the binary size, and since I have multiple programs that all use it, I decided to use dynamic linking to save resources. However, after searching around the web I found nothing useful, and finally worked it out through a discussion with ChatGPT. Below is the way to configure CMake to dynamically link spdlog.

Steps

1. Write spdlog.cmake

First, write a CMake module configuration file spdlog.cmake and put it under ${PROJECT_SOURCE_DIR}/cmake. The file content is as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Set spdlog to be built as a shared library

# build shared option
option(SPDLOG_BUILD_SHARED "Build shared library" ON)
# precompiled headers option
option(SPDLOG_ENABLE_PCH "Build static or shared library using precompiled header to speed up compilation time" ON)
# build position independent code
option(SPDLOG_BUILD_PIC "Build position independent code (-fPIC)" ON)

# Add the spdlog library
add_subdirectory(${PROJECT_SOURCE_DIR}/lib/spdlog)

# Set the output path of the spdlog library's lib
set_target_properties(spdlog PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/output/lib)

2. Include the Module Configuration

Add a line to the CMakeLists.txt at the project root:

1
include(${PROJECT_SOURCE_DIR}/cmake/spdlog.cmake) # Load the spdlog module

Add the following to the sub CMakeLists.txt where spdlog is used:

1
2
3
4
set(LIB_SPDLOG_ROOT ${PROJECT_SOURCE_DIR}/path/to/spdlog) # Set the root path of the spdlog library
include_directories(${LIB_SPDLOG_ROOT}/include) # Set the include file path of the spdlog library
link_directories(${PROJECT_SOURCE_DIR}/output/lib) # Set the library linking path
target_link_libraries(<target> spdlog)