使用cmake写一个可以被其他cmake文件find_package的包,并给出详细代码
时间: 2024-02-09 22:10:48 浏览: 186
以下是一个使用CMake编写可被其他CMake文件`find_package`的包的示例,其中包含了库文件和头文件:
1. 创建一个库
在CMakeLists.txt中定义库,例如:
```
# CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(mylib)
add_library(mylib SHARED mylib.cpp) # 创建一个共享库
install(TARGETS mylib
EXPORT mylib-targets
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
RUNTIME DESTINATION bin
INCLUDES DESTINATION include)
install(FILES mylib.h DESTINATION include)
```
2. 创建CMake配置文件
创建一个名为`mylib-config.cmake.in`的文件,该文件包含了包的版本号、库文件路径等信息。注意,该文件中需要使用`@VAR@`的形式来引用变量,CMake将在安装时将这些变量替换为实际值。例如:
```
# mylib-config.cmake.in
@PACKAGE_INIT@
set(MYLIB_INCLUDE_DIRS "${CMAKE_INSTALL_PREFIX}/include")
set(MYLIB_LIBRARIES "${CMAKE_INSTALL_PREFIX}/lib/libmylib.so")
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/mylib-config.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/mylib-config.cmake @ONLY)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/mylib-config.cmake
DESTINATION lib/cmake/mylib)
```
该文件中使用了`@PACKAGE_INIT@`宏来加载CMake的基本配置信息。
3. 创建CMake模块文件
创建一个名为`FindMylib.cmake`的文件,该文件包含了一个find_package函数,用于查找并加载CMake配置文件。例如:
```
# FindMylib.cmake
find_package(PkgConfig)
pkg_check_modules(PC_MYLIB QUIET mylib)
find_path(MYLIB_INCLUDE_DIR mylib.h
HINTS ${PC_MYLIB_INCLUDE_DIRS} ${CMAKE_INSTALL_PREFIX}/include)
find_library(MYLIB_LIBRARY NAMES mylib
HINTS ${PC_MYLIB_LIBDIR} ${CMAKE_INSTALL_PREFIX}/lib)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Mylib
REQUIRED_VARS MYLIB_INCLUDE_DIR MYLIB_LIBRARY
VERSION_VAR MYLIB_VERSION)
if(Mylib_FOUND)
set(MYLIB_LIBRARIES ${MYLIB_LIBRARY})
set(MYLIB_INCLUDE_DIRS ${MYLIB_INCLUDE_DIR})
endif()
mark_as_advanced(MYLIB_INCLUDE_DIR MYLIB_LIBRARY)
```
该文件中使用了`find_package_handle_standard_args`函数来检查包是否已找到,并将结果保存在`Mylib_FOUND`变量中。此外,还定义了`MYLIB_INCLUDE_DIRS`和`MYLIB_LIBRARIES`变量,用于在其他CMake文件中引用。
4. 安装包
在CMakeLists.txt中添加以下内容,用于安装CMake配置文件和模块文件:
```
# CMakeLists.txt
install(EXPORT mylib-targets
FILE mylib-targets.cmake
NAMESPACE mylib::
DESTINATION lib/cmake/mylib)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/mylib-config.cmake
DESTINATION lib/cmake/mylib)
install(FILES FindMylib.cmake
DESTINATION lib/cmake/mylib)
```
5. 使用包
在其他CMake文件中,可以使用`find_package`函数来查找并加载该包,例如:
```
# CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(myapp)
find_package(mylib REQUIRED)
add_executable(myapp main.cpp)
target_link_libraries(myapp PRIVATE mylib::mylib)
```
注意,上述代码中的`mylib`是指在FindMylib.cmake中定义的包名,而不是库/二进制文件的名称。
阅读全文