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})