前几个帖子构建MathFunctions库并没有特别设置生成的是静态库还是动态库,观察linux系统下生成的文件,可以看到有一个“libMathFunctions.a”文件,说明默认生成的是静态库。
以下讲述动态库的建立:
1、add_library()
add_library(<name> [STATIC | SHARED | MODULE]
[EXCLUDE_FROM_ALL]
[<source>...])
add_library()函数是通过源文件构建一个名为的库,库的类型由[STATIC | SHARED | MODULE]设定:
static —— 静态库 —— (lib.a or .lib)
shared —— 动态库 —— (lib.so or .dll)
module—— 模块库
2、动态库
修改顶层CMakeLists.txt,将MathFunctions库独立出来:
make_minimum_required(VERSION 3.10)
# 设置工程名
project(CalculateSqrt VERSION 1.0)
# 设置built目录
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
add_subdirectory(MathFunctions)
# 添加文件
add_executable(CalculateSqrt ${DIR_SRCS})
target_link_libraries(CalculateSqrt PUBLIC MathFunctions)
在MathFunctions下新建MathFunctions.h来设置动态库的导入导出:
#if define(MathFunctions_EXPORTS)
#define MathFunctions_API __declspec(dllexport)
#else
#define MathFunctions_API __declspec(dllimport)
#endif
设置API为MathFunctions_API,让MySqrt.h包含MathFunctions.h头文件。
#include "MathFunctions.h"
MathFunctions_API int MySqrt(int x);
最后修改MathFunctions/CMakeLists.txt,将MathFunctions设置为动态库。
# 将本目录中的源文件设置为MathFunctions_SOURCE
aux_source_directory(. MathFunctions_SOURCE)
#设置为动态库
add_library(MathFunctions SHARED ${MathFunctions_SOURCE})
#设置包含路径
target_include_directories(
MathFunctions
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
)
#定义windows上构建动态库中使用的 declspec(dllexport)
target_compile_definitions(MathFunctions PRIVATE MathFunctions_EXPORTS)
#安装规则
install(TARGETS MathFunctions
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
install(FILES MySqrt.h DESTINATION include)
cmake构建之后生成的文件:
3、选择建立静态库或动态库
设置一个开关选项,控制建立静态库或动态库。在MathFunctions/CMakeLists.txt文件中添加:
#开关项
option(BUILD_SHARED_LIBS "Build using shared libraries" ON)
if(BUILD_SHARED_LIBS)
#设置为动态库
add_library(MathFunctions SHARED ${MathFunctions_SOURCE})
target_compile_definitions(MathFunctions PRIVATE MathFunctions_EXPORTS)
else()
add_library(MathFunctions STATIC ${MathFunctions_SOURCE})
endif()
相应地修改MathFunctions.h文件:
#if defined(BUILD_SHARED_LIBS)
#if define(MathFunctions_EXPORTS)
#define MathFunctions_API __declspec(dllexport)
#else
#define MathFunctions_API __declspec(dllimport)
#endif
#else
#define MathFunctions_API
#endif
命令行输入
cmake .. -D BUILD_SHARED_LIBS=ON
cmake --build .
或者
cmake .. -D BUILD_SHARED_LIBS=ON
cmake --build .
观察生成文件的不同。