[英]cmake: compile a shared library and executable
我想建立:
对于库,我有以下 CMakeLists.txt 文件:
cmake_minimum_required(VERSION 3.13.4)
project(driver C)
set(CMAKE_C_STANDARD 99)
set(LIB_PATH "../../libdriver")
include_directories(${LIB_PATH})
include_directories(driver ${LIB_PATH}/uart)
add_library(driver SHARED
${LIB_PATH}/libdriver.c
${LIB_PATH}/uart/uart.c)
我创建了LIB_PATH
变量,因为 lib 编译所需的文件在树之外。
现在我有了可执行的 CMakeLists.txt,我想使用之前编译的 dll 文件。
cmake_minimum_required(VERSION 3.13.4)
project(proj_exe C)
set(CMAKE_C_STANDARD 99)
set(LIB_PATH "../../libdriver") # so I have the headers
set(MAIN_PATH "../../project") # the main.c file located here
include_directories(${LIB_PATH})
include_directories(driver ${LIB_PATH}/uart)
# what to do now to compile the executable with the dll
您可能希望在本地安装驱动程序库并使用 cmake 的功能生成导入脚本。 在使用 lib 的项目中,您可以使用find_package
添加 dll 作为导入的目标,允许您使用target_link_library
链接它:
add_library(driver SHARED
${LIB_PATH}/libdriver.c
${LIB_PATH}/uart/uart.c)
# attach the info to the target here
target_include_directories(driver PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/${LIB_PATH}>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/${LIB_PATH}/uart>
$<INSTALL_INTERFACE:include>
$<INSTALL_INTERFACE:include/uart>
)
install(TARGETS driver EXPORT driver
RUNTIME DESTINATION bin
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
)
# usually there's a lib just containing the public headers
# that can be copied, but yours seems to contain the source files too;
# not enough info though to separate headers from sources though, so we'll just copy everything
install(DIRECTORY ${LIB_PATH}/ DESTINATION include)
install(EXPORT base DESTINATION cmake FILE base-config.cmake)
建成后你应该可以做
cmake --install build_dir --prefix install_path
这允许您使用find_package
从安装目录导入文件,假设您已将其添加到CMAKE_PREFIX_PATH
cmake -D CMAKE_PREFIX_PATH=install_path -S ... -B ...
find_package(driver REQUIRED CONFIG)
add_executable(foo ...)
target_link_libraries(foo PRIVATE driver)
您可能需要稍微调整描述中的路径以指向使用相对于当前工作目录的正确位置...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.