动态链接spdlog的cmake配置#
由于spdlog仅头文件形式编译会大大增加二进制文件大小,同时我有多个程序都要使用,为了节省资源,考虑使用动态链接,但是网上查了一圈都没有效内容,最后跟ChatGPT讨论出来了。以下给出cmake配置动态链接spdlog的办法。
1. 编写spdlog.cmake
#
首先编写一个cmake模块配置文件spdlog.cmake
放到${PROJECT_SOURCE_DIR}/cmake
下,文件内容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# 设置spdlog编译为动态库
# 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)
# 添加spdlog库
add_subdirectory(${PROJECT_SOURCE_DIR}/lib/spdlog)
# 设置spdlog库的lib输出路径
set_target_properties(spdlog PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/output/lib)
|
2. 引入模块配置#
在项目根路径的CMakeLists.txt
添加一行:
1
|
include(${PROJECT_SOURCE_DIR}/cmake/spdlog.cmake) # 加载spdlog模块
|
3. 动态链接spdlog
#
在要使用spdlog
的子CMakeLists.txt
中添加:
1
2
3
4
|
set(LIB_SPDLOG_ROOT ${PROJECT_SOURCE_DIR}/path/to/spdlog) # 设置spdlog库根路径
include_directories(${LIB_SPDLOG_ROOT}/include) # 设置spdlog库头文件路径
link_directories(${PROJECT_SOURCE_DIR}/output/lib) # 设置链接库路径
target_link_libraries(<target> spdlog)
|