調整 CMakeLists.txt for OpenCV 4.1.0(已安裝多版本opencv@2, opencv@3...)

動機:想要練習 OpenCV 4.1.0 的C++程式,又想要跨平台於 Mac/Windows 之間,如何撰寫 CMakeLists.txt 來建構呢?!

準備環境
1.macOS Mojave v.10.14.5 / Windows 10
2.Python 3.7.3
3.CLion 2019.1
4.OpenCV 4.1.0(同時已安裝opencv@2, opencv@3)
5.CMake 3.14.4

實作步驟
1.基本上若只有安裝一個獨立版本的OpenCV就不會有此問題,但是我的環境是如此複雜,又要兼容 OpenCV2/OpenCV3/OpenCV4,又要同時去寫 c++ 及 python 程式,又要跨 Mac/Windows/Ubuntu 平台,只好想辦法克服了...
2.以下提供我try了很久的 CMakeLists.txt

# CMake 最低版本号要求
cmake_minimum_required( VERSION 3.14 )

# Enable C++11
set( CMAKE_CXX_STANDARD 11 )
set( CMAKE_CXX_STANDARD_REQUIRED TRUE )
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11" )

set( name display_image )
# 项目信息
project( ${name} )
# Print this project name
message( STATUS "Project name: ${name}" )

# 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
if(WIN32)
    set( OpenCV_DIR "D:/Program Files/opencv/build/x64/vc15/lib" )
endif()
if(APPLE)
    set( OpenCV_DIR "/usr/local/Cellar/opencv/4.1.0_2/lib/cmake/opencv4" )
endif()

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_LIBS}" )
message( STATUS "    include path: ${OpenCV_INCLUDE_DIRS}" )
include_directories( ${OpenCV_INCLUDE_DIRS} )

# 指定生成目标
add_executable( ${name} ${name}.cpp )
target_link_libraries( ${name} ${OpenCV_LIBS} )

3.有了以上的檔案(只需要修改 name 即可),配合 CLion 的編譯環境,寫程式就方便多多了!! :-)

心得


參攷

留言