简体   繁体   中英

How to know version of library found by CMake?

I'm currently developing a C++ project that uses CMake files and OpenCV among other libraries. My target would be to be able to compile my code both with version 2.4.something and with 3.0.

In order to do so, I thought of using CMake configured to set a variable indicating whether the OpenCV package found in the configuration phase has a version greater or equal to 3.0. Using this variable I can then include or exclude ad-hoc parts of my code.

However I was not able to find anywhere how can I know in a CMake file the version of a found package.

The pseudo code of my CMake file would look something like this:

....
find_package(OpenCV 2.4 REQUIRED)
if(OpenCV_Version >= 3)
    set (OpenCV_3 1)
else
    set (OpenCV_3 0)
endif(OpenCV_Version)
....

Is it possible to do this or am I doing something wrong?

From CMake documentation on find_package :

If the version is acceptable the following variables are set:

<package>_VERSION
    full provided version string
<package>_VERSION_MAJOR
    major version if provided, else 0
<package>_VERSION_MINOR
    minor version if provided, else 0
<package>_VERSION_PATCH
    patch version if provided, else 0
<package>_VERSION_TWEAK
    tweak version if provided, else 0
<package>_VERSION_COUNT
    number of version components, 0 to 4

You may use either variable OpenCV_VERSION with full version string for comparing using VERSION_* modes of if() command:

if(OpenCV_VERSION VERSION_LESS "3.0")
    # 2.4 version
else()
    # 3.0 version
endif()

or version-component variables with number comparision:

if(OpenCV_VERSION_MAJOR LESS 3)
    # 2.4 version
else()
    # 3.0 version
endif()

OpenCV provides a built in constant for this:

CV_MAJOR_VERSION

Using this constant you're able to easily write version dependent code.

#if CV_MAJOR_VERSION >= 3
    //OpenCV 3.x code
#else
    //OpenCV 2.4.x code
#endif

If you are using FindPkgConfig , you can also use its pkg_search_module command.

pkg_search_module(<PREFIX> [REQUIRED] [QUIET]
                  [NO_CMAKE_PATH] [NO_CMAKE_ENVIRONMENT_PATH]
                  <MODULE> [<MODULE>]*)

It then sets a <package>_VERSION variable if it finds the module.

include(FindPkgConfig)

pkg_search_module(OPENCV    REQUIRED    opencv)

message(STATUS "Got OpenCV ${OPENCV_VERSION}")
if (${OPENCV_VERSION} VERSION_GREATER_EQUAL "3.0.0")
    message(STATUS "Got OpenCV 3+")
else()
    message(STATUS "Got OpenCV <3")
endif()

That prints out something like this:

-- Checking for one of the modules 'opencv'
-- Got OpenCV 3.2.0
-- Got OpenCV 3+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM