linking opencv libraries included as an external project via cmake

Vyacheslav picture Vyacheslav · Mar 23, 2014 · Viewed 23.4k times · Source

I'm relatively new to cmake and after days of struggling couldn't figure out the following thing:

I have a project that depends on opencv (which is a cmake project on its own) and I want to statically link opencv libraries. What I'm doing is I have a copy of opencv source code in my project and include it into my CMakeLists.txt via

ExternalProject_Add(my_copy_of_opencv_project
   CMAKE_ARGS -D BUILD_SHARED_LIBS=NO ...
   CMAKE_INSTALL_PREFIX=${MY_OPENCV_INSTALL_DIR} 
   SOURCE_DIR ${PATH_TO_OPENCV_SRCS} 
)

All built nicely and where I have problem is that I cannot reliably determine where the opencv libraries will be. E.g. on linux/mac there are in ${MY_OPENCV_INSTALL_DIR}/lib and are named as libopencv_core.a whereas on 32-bit Windows with VS 2012 installed the libs are in ${MY_OPENCV_INSTALL_DIR}/lib/x86/vc11/staticlib and for the Debug configuration the libs named like opencv_core247d.lib.

So the question is can I somehow obtain a list of all libraries produced by the OpenCV build (and the root lib folder) and link them via something like target_link_libraries(mylib opencv_core ...)?

Maybe I'm doing something wrong or overcomplicated. So what I basically want is to compile my embedded opencv source tree statically and link against its libraries in a "cross-plaformish" way.

Any pointers are highly appreciated! Thanks!

Answer

maxint picture maxint · Mar 24, 2014

The best solution to use cmake with OpenCV project is:

  1. Compile OpenCV as shared / static libraries with OpenCV's cmake build system.
  2. In your project's CMakeLists.txt

For example (CMakeLists.txt):

cmake_minimum_required(VERSION 2.8.12)
project(test_project)

# OpenCV_DIR could also be read from system environment variable.
if(WIN32)
  set(OpenCV_DIR "d:/libs/opencv-2.4.8/build")
else()
  set(OpenCV_DIR "/usr/lib/opencv")
endif()
find_package(OpenCV REQUIRED COMPONENTS core imgproc highgui)

include_directories(${OpenCV_INCLUDE_DIRS}) # not needed for opencv>=4.0
add_executable(test main.cpp)
target_link_libraries(test ${OpenCV_LIBS})

It works in cross-platforms.