CMake如何查找包

31moq8wy  于 2023-11-19  发布在  其他
关注(0)|答案(1)|浏览(142)

我有一个CMake,可以将OpenCV添加到项目中。
我使用以下代码将OpenCV添加到我的项目中:

if (MSVC)
    file(TO_CMAKE_PATH $ENV{OPENCV_ROOT} OpenCV_DIR)
    IF(NOT OpenCV_DIR)
        MESSAGE( FATAL_ERROR "Please point the environment variable OpenCV_ROOT to the root directory of OpenCV installation. required openCv V 4.2.x as minimum")
    ENDIF()
    set(BUILD_SHARED_LIBS OFF)
    find_package(OpenCV 4.2.0 REQUIRED)
else (MSVC)
    set(BUILD_SHARED_LIBS ON)
    find_package(OpenCV COMPONENTS core highgui imgproc imgcodecs videoio photo stitching flann ml features2d calib3d objdetect REQUIRED)
endif(MSVC)

字符串
如果我没有定义OpenCV_root环境变量,CMake找不到OpenCV。但是如果我定义了它,我会得到这样的警告:

CMake Warning (dev) at CMakeLists.txt:36 (find_package):
  Policy CMP0074 is not set: find_package uses <PackageName>_ROOT variables.
  Run "cmake --help-policy CMP0074" for policy details.  Use the cmake_policy
  command to set the policy and suppress this warning.

  Environment variable OpenCV_ROOT is set to:

    D:\local\opencv

  For compatibility, CMake is ignoring the variable.
This warning is for project developers.  Use -Wno-dev to suppress it.


那么,如果我没有定义openCV_root环境变量,CMake如何找到OpenCV呢?
同样的问题也适用于其他软件包(比如boost,我得到了同样的警告),我们应该定义一个env变量吗?
如果我没有定义一个env变量,OpenCV如何找到这个包?

y0u0uwnf

y0u0uwnf1#

CMP 0074策略的description说明:
在CMake 3.12及更高版本中,find_package(<PackageName>)命令现在搜索由<PackageName>_ROOT CMake变量和<PackageName>_ROOT环境变量指定的前缀.此策略提供了与尚未更新的项目的兼容性,以避免将<PackageName>_ROOT变量用于其他目的。
也就是说,在你的项目中,你需要消除使用OPENCV_ROOT变量的目的,而不是直接影响find_package(OpenCV)行为。
在较新的CMake中,此变量被自动使用:

# This sets CMP0074 to NEW.
cmake_minimum_required(VERSION 3.12) # Or bigger version
set(BUILD_SHARED_LIBS OFF)
# If `OPENCV_ROOT` variable is set, it will be used in the next call without a warning.
find_package(OpenCV 4.2.0 REQUIRED)

字符串
如果你想让你的项目有一个关于OpenCV安装的提示用于其他目的,请使用不同名称的变量。

# We want to support old CMake versions too!
cmake_minimum_required(VERSION 3.11) # Or lower version

# Use `OPENCV_INSTALL_PREFIX` environment variable for set `OpenCV_DIR`, which helps CMake to find OpenCV.
# This setting works for both new and old CMake versions.
file(TO_CMAKE_PATH $ENV{OPENCV_INSTALL_PREFIX} OpenCV_DIR)
IF(NOT OpenCV_DIR)
    MESSAGE( FATAL_ERROR "Please point the environment variable OPENCV_INSTALL_PREFIX to the root directory of OpenCV installation. required openCv V 4.2.x as minimum")
ENDIF()
set(BUILD_SHARED_LIBS OFF)
find_package(OpenCV 4.2.0 REQUIRED)


或者,您也可以禁用CMP0074策略,使用OPENCV_ROOT变量来实现您的目的。但不推荐

# 'find_package' won't use `_ROOT` variable. This suppress the corresponding warning. 
cmake_policy(SET CMP0074 OLD)
file(TO_CMAKE_PATH $ENV{OPENCV_ROOT} OpenCV_DIR)
IF(NOT OpenCV_DIR)
    MESSAGE( FATAL_ERROR "Please point the environment variable OpenCV_ROOT to the root directory of OpenCV installation. required openCv V 4.2.x as minimum")
ENDIF()
set(BUILD_SHARED_LIBS OFF)
find_package(OpenCV 4.2.0 REQUIRED)

相关问题