CMake选择静态库或动态库

前几个帖子构建MathFunctions库并没有特别设置生成的是静态库还是动态库,观察linux系统下生成的文件,可以看到有一个“libMathFunctions.a”文件,说明默认生成的是静态库。
以下讲述动态库的建立:

1、add_library()

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 .

观察生成文件的不同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值