CMake(2): find_package 命令

1 简介

CMake 允许调用find_...()命令以查找指定的文件、库、或者整个package.主要有find_file()find_path()find_program()find_library()find_package().

本文主要介绍最常用的find_package().

CMake中package有两种定义方式:module 和 config details.

find_package(<name>)工作流程:

  1. CMake 查找CMAKE_MODULE_PATH下的Find<name>.cmake文件。
  2. 如果找到Find<name>.cmake,则可以根据2的变量进行配置。
  3. 如果没有找到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})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章