1 简介
CMake 允许调用find_...()
命令以查找指定的文件、库、或者整个package.主要有find_file()
、find_path()
、find_program()
、find_library()
、find_package()
.
本文主要介绍最常用的find_package()
.
CMake中package有两种定义方式:module 和 config details.
find_package(<name>)
工作流程:
- CMake 查找
CMAKE_MODULE_PATH
下的Find<name>.cmake
文件。- 如果找到
Find<name>.cmake
,则可以根据2的变量进行配置。- 如果没有找到
Find<name>.cmake
,CMake查找CMAKE_PREFIX_PATH
下的<name>Config.cmake
文件完成配置,或者期望用户向变量<name>_DIR
指定<name>Config.cmake
文件的路径。
注意:Find<name>.cmake
和<name>Config.cmake
文件内容可以完全相同。推荐使用CMAKE_PREFIX_PATH
指定搜索路径。
2 相关变量
不同的宏使用的变量可能有所差异,需要进行辨别。下面是一组常用变量:
<name>_FOUND // true if the package was found
<name>_INCLUDE_DIRS // a list of directories containing the package's include files
<name>_LIBRARIES // a list of directories containing the package's libraries
<name>_LINK_DIRECTORIES // the list of the package's libraries
3 实例
OpenCV的 cpp 例子中,最简单的方式是使用以下命令配置生成:
cmake -DCMAKE_PREFIX_PATH=/path/to/opencv /path/to/source
或者通过指定OpenCV_DIR
变量:
先查找FindOpenCV.cmake
文件位置:
$ sudo find / -iname findopencv.cmake
find: ‘/run/user/1000/gvfs’: Permission denied
find: ‘/tmp/.mount_ShadowSiHOjN’: Permission denied
发现该文件不存在,再查找OpenCVConfig.cmake
文件:
$ sudo find / -iname opencvconfig.cmake
/usr/local/opencv4/lib/cmake/opencv4/OpenCVConfig.cmake
find: ‘/run/user/1000/gvfs’: Permission denied
/home/ywq/Downloads/OpenCV/opencv-4.0.0/build/unix-install/OpenCVConfig.cmake
/home/ywq/Downloads/OpenCV/opencv-4.0.0/build/OpenCVConfig.cmake
find: ‘/tmp/.mount_ShadowSiHOjN’: Permission denied
所以可以在CMakeLists.txt
文件find_package(OpenCV REQUIRED)
前设置OpenCV_DIR
:
# cmake needs this line
cmake_minimum_required(VERSION 3.1)
# Enable C++11
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
# Define project name
project(opencv_example_project)
# Find OpenCV, you may need to set OpenCV_DIR variable
# to the absolute path to the directory containing OpenCVConfig.cmake file
# via the command line or GUI
set(OpenCV_DIR /usr/local/opencv4/lib/cmake/opencv4)
find_package(OpenCV REQUIRED)
# If the package has been found, several variables will
# be set, you can find the full list with descriptions
# in the OpenCVConfig.cmake file.
# Print some message showing some of them
message(STATUS "OpenCV library status:")
message(STATUS " config: ${OpenCV_DIR}")
message(STATUS " version: ${OpenCV_VERSION}")
message(STATUS " libraries: ${OpenCV_LIBRARIES}")
message(STATUS " include path: ${OpenCV_INCLUDE_DIR}")
# Declare the executable target built from your sources
add_executable(opencv_example example.cpp)
# Link your application with OpenCV libraries
target_link_libraries(opencv_example ${OpenCV_LIBRARIES})