Can't link a project using cmake with OpenCV and LibTorch - opencv

I asked a similar question about linking a project with OpenCV a few days ago. I got that working, but now I've hit a very weird problem using CMake and adding LibTorch to the project.
If I only use OpenCV in the project, everything compiles, links, and runs fine.
But if I add Torch to CMakeLists.txt, I get a linker error:
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
set(CMAKE_VERBOSE_MAKEFILE ON)
project(torchscriptie)
find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )
find_package(Torch HINTS "/usr/local/libtorch")
message(STATUS "TORCH_LIBRARIES = ${TORCH_LIBRARIES}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")
add_executable(torchscriptie main.cpp)
target_link_libraries( torchscriptie ${OpenCV_LIBS} )
target_link_libraries(torchscriptie "${TORCH_LIBRARIES}")
set_property(TARGET torchscriptie PROPERTY CXX_STANDARD 14)
This CMakeLists.txt file causes this error:
CMakeFiles/torchscriptie.dir/main.cpp.o: In function `main':
/code/cpp/torchscriptie/main.cpp:18: undefined reference to `cv::imread(std::string const&, int)'
/code/cpp/torchscriptie/main.cpp:24: undefined reference to `cv::namedWindow(std::string const&, int)'
/code/cpp/torchscriptie/main.cpp:25: undefined reference to `cv::imshow(std::string const&, cv::_InputArray const&)'
collect2: error: ld returned 1 exit status
Here's the command:
/usr/bin/c++ -g -rdynamic CMakeFiles/torchscriptie.dir/main.cpp.o -o torchscriptie -Wl,-rpath,/usr/local/lib:/usr/local/libtorch/lib /usr/local/lib/libopencv_gapi.so.4.3.0 /usr/local/lib/libopencv_stitching.so.4.3.0 /usr/local/lib/libopencv_alphamat.so.4.3.0 /usr/local/lib/libopencv_aruco.so.4.3.0 /usr/local/lib/libopencv_bgsegm.so.4.3.0 /usr/local/lib/libopencv_bioinspired.so.4.3.0 /usr/local/lib/libopencv_ccalib.so.4.3.0 /usr/local/lib/libopencv_dnn_objdetect.so.4.3.0 /usr/local/lib/libopencv_dnn_superres.so.4.3.0 /usr/local/lib/libopencv_dpm.so.4.3.0 /usr/local/lib/libopencv_face.so.4.3.0 /usr/local/lib/libopencv_freetype.so.4.3.0 /usr/local/lib/libopencv_fuzzy.so.4.3.0 /usr/local/lib/libopencv_hdf.so.4.3.0 /usr/local/lib/libopencv_hfs.so.4.3.0 /usr/local/lib/libopencv_img_hash.so.4.3.0 /usr/local/lib/libopencv_intensity_transform.so.4.3.0 /usr/local/lib/libopencv_line_descriptor.so.4.3.0 /usr/local/lib/libopencv_quality.so.4.3.0 /usr/local/lib/libopencv_rapid.so.4.3.0 /usr/local/lib/libopencv_reg.so.4.3.0 /usr/local/lib/libopencv_rgbd.so.4.3.0 /usr/local/lib/libopencv_saliency.so.4.3.0 /usr/local/lib/libopencv_stereo.so.4.3.0 /usr/local/lib/libopencv_structured_light.so.4.3.0 /usr/local/lib/libopencv_superres.so.4.3.0 /usr/local/lib/libopencv_surface_matching.so.4.3.0 /usr/local/lib/libopencv_tracking.so.4.3.0 /usr/local/lib/libopencv_videostab.so.4.3.0 /usr/local/lib/libopencv_viz.so.4.3.0 /usr/local/lib/libopencv_xfeatures2d.so.4.3.0 /usr/local/lib/libopencv_xobjdetect.so.4.3.0 /usr/local/lib/libopencv_xphoto.so.4.3.0 /usr/local/libtorch/lib/libtorch.so /usr/local/libtorch/lib/libc10.so /usr/local/lib/libopencv_shape.so.4.3.0 /usr/local/lib/libopencv_highgui.so.4.3.0 /usr/local/lib/libopencv_datasets.so.4.3.0 /usr/local/lib/libopencv_plot.so.4.3.0 /usr/local/lib/libopencv_text.so.4.3.0 /usr/local/lib/libopencv_dnn.so.4.3.0 /usr/local/lib/libopencv_ml.so.4.3.0 /usr/local/lib/libopencv_phase_unwrapping.so.4.3.0 /usr/local/lib/libopencv_optflow.so.4.3.0 /usr/local/lib/libopencv_ximgproc.so.4.3.0 /usr/local/lib/libopencv_video.so.4.3.0 /usr/local/lib/libopencv_videoio.so.4.3.0 /usr/local/lib/libopencv_imgcodecs.so.4.3.0 /usr/local/lib/libopencv_objdetect.so.4.3.0 /usr/local/lib/libopencv_calib3d.so.4.3.0 /usr/local/lib/libopencv_features2d.so.4.3.0 /usr/local/lib/libopencv_flann.so.4.3.0 /usr/local/lib/libopencv_photo.so.4.3.0 /usr/local/lib/libopencv_imgproc.so.4.3.0 /usr/local/lib/libopencv_core.so.4.3.0 -Wl,--no-as-needed,/usr/local/libtorch/lib/libtorch_cpu.so -Wl,--as-needed /usr/local/libtorch/lib/libc10.so -lpthread -Wl,--no-as-needed,/usr/local/libtorch/lib/libtorch.so -Wl,--as-needed
I've tried a lot of different combination of commands, but I cannot figure our what's wrong.
When I echo the TORCH_LIBRARIES variable, it returns:
torch;torch_library;/usr/local/libtorch/lib/libc10.so
If I change the libaries, for example to torch_cpu, I'm able to link OpenCV libraries.
set(TORCH_LIBRARIES torch_cpu)
I have no idea why Torch libraries are causing link errors with OpenCV in the same project.
Any suggestions would be great.

Not sure if this fixes your problem, but I had also a few problems like yours. It is working for me with a cmake file including this:
cmake_minimum_required(VERSION 3.14 FATAL_ERROR)
project(MyProject)
set(CMAKE_CXX_STANDARD 14)
list(APPEND CMAKE_PREFIX_PATH "folderToLibtorch/libtorch/share/cmake")
find_package(Torch REQUIRED)
find_package(OpenCV REQUIRED)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -lm -ldl")
add_executable(MyProject ...some project files...)
target_link_libraries(MyProject ${TORCH_LIBRARIES} ${OpenCV_LIBS})
set_property(TARGET MyProject PROPERTY CXX_STANDARD 14)
So make sure list(APPEND CMAKE_PREFIX_PATH "folderToLibtorch/libtorch/share/cmake") is included, this did the trick for me. Also take care to get the right libtorch version from pytorch maybe you should use the lower link and not the "pre-..." version.
Good Luck

The problem is in the version libtorch.
Please use libtorch-cxx11-abi-shared-with-deps not libtorch-shared-with-deps. It is library conflict between libtorch and opencv.
Solution here.
There is my version of CMakeList.txt with CUDA+LIBTORCH+OPENCV support:
cmake_minimum_required(VERSION 3.8 FATAL_ERROR)
SET(CUDA_HOME /usr/local/cuda)
SET(CMAKE_CUDA_COMPILER /usr/local/cuda/bin/nvcc)
SET(CUDA_TOOLKIT_ROOT_DIR /usr/local/cuda)
# SET(CUDA_CUBLAS_LIBRARIES /usr/local/cuda/lib64)
SET(CUDA_cublas_device_LIBRARY /usr/local/cuda/lib64)
# SET(CMAKE_CUDA_COMPILER_ENV_VAR /usr/local/cuda/bin/nvcc)
SET(CUDA_INCLUDE_DIRS /usr/local/cuda/include)
if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES)
set(CMAKE_CUDA_ARCHITECTURES 50)
endif()
set(OpenCV_DIR /usr/local/lib/cmake/opencv4)
# set(OpenCV_DIR /usr/local/lib)
project(cmake_and_cuda LANGUAGES CXX CUDA)
include(CTest)
find_package(CUDA REQUIRED)
# libtorch with OpenCV support , with fixed BUG !
list(APPEND CMAKE_PREFIX_PATH ./libtorch)
find_package(Torch REQUIRED)
message(STATUS "TORCH_LIBRARIES = ${TORCH_LIBRARIES}")
find_package(OpenCV REQUIRED)
message(STATUS "OpenCV_LIBS = ${OpenCV_LIBS}")
# ADD OWN CUDA FILES FOR BUILD LIBRARY.
add_library(particles_new_lib STATIC
torch_module_plus_cuda.cu
torch_module_plus_cuda.h
)
target_compile_features(particles_new_lib PUBLIC cxx_std_14)
# We need to explicitly state that we need all CUDA files in the
# particles_new_lib library to be built with -dc as the member functions
# could be called by other libraries and executables
set_target_properties( particles_new_lib
PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
add_executable(particle_cuda_test torch_and_cuda_call.cpp)
set_property(TARGET particle_cuda_test
PROPERTY CUDA_SEPARABLE_COMPILATION ON)
# LINK ALL LIBRARIES TO TARGET particle_cuda_test
target_link_libraries(particle_cuda_test PRIVATE ${TORCH_LIBRARIES} ${OpenCV_LIBS} particles_new_lib)
# LINK LIBRARIES
target_link_libraries(particle_cuda_test PRIVATE particles_new_lib)
set_property(TARGET particle_cuda_test PROPERTY CXX_STANDARD 14)

Related

PCL can't find header file

/home/ubuntu/emvs_ws/src/rpg_emvs/mapper_emvs/src/realtime.cpp:25:62: fatal error: pcl/registration/impl/incremental_registration.hpp: No such file or directory
compilation terminated.
rpg_emvs/mapper_emvs/CMakeFiles/realtime_emvs.dir/build.make:62: recipe for target 'rpg_emvs/mapper_emvs/CMakeFiles/realtime_emvs.dir/src/realtime.cpp.o' failed
make[2]: *** [rpg_emvs/mapper_emvs/CMakeFiles/realtime_emvs.dir/src/realtime.cpp.o] Error 1
I'm getting this error after catkin_make
Theses are the includes in realtime.cpp
#include <pcl/registration/incremental_registration.h>
#include <pcl/registration/icp.h>
CMakeLists.txt file
project(mapper_emvs)
cmake_minimum_required(VERSION 2.8.3)
find_package(catkin_simple REQUIRED)
catkin_simple(ALL_DEPS_REQUIRED)
set(CMAKE_BUILD_TYPE RelWithDebInfo) # Release, RelWithDebInfo
set(CMAKE_CXX_FLAGS "-O3 -fopenmp -std=c++11 ${CMAKE_CXX_FLAGS}")
## Generate dynamic reconfigure parameters in the 'cfg' folder
##generate_dynamic_reconfigure_options(
## cfg/EMVSCfg.cfg
##)
set(HEADERS
include/mapper_emvs/mapper_emvs.hpp
include/mapper_emvs/data_loading.hpp
include/mapper_emvs/depth_vector.hpp
include/mapper_emvs/trajectory.hpp
include/mapper_emvs/geometry_utils.hpp
include/mapper_emvs/median_filtering.hpp
)
set(SOURCES
src/mapper_emvs.cpp
src/data_loading.cpp
src/median_filtering.cpp
)
option(DEFINE_USE_INVERSE_DEPTH "Use linear spacing in inverse depth (if OFF, will use linear spacing in depth)" ON)
if(DEFINE_USE_INVERSE_DEPTH)
add_definitions(-DUSE_INVERSE_DEPTH)
endif(DEFINE_USE_INVERSE_DEPTH)
cs_add_library(${PROJECT_NAME} ${SOURCES} ${HEADERS})
# Executables
################################################################################
cs_add_executable(run_emvs src/main.cpp)
target_link_libraries(run_emvs ${PROJECT_NAME})
cs_add_executable(realtime_emvs src/realtime.cpp)
add_dependencies(realtime_emvs ${PROJECT_NAME}_gencfg)
target_link_libraries(realtime_emvs ${PROJECT_NAME})
################################################################################
cs_install()
cs_export()
Note that I did Catkin_make not catkin build, I don;t know if this makes a difference.
I'm asked to add more details, so please ignore this line :)
You need to add PCL library in your CMakeLists.txt file as follows:
project(mapper_emvs)
cmake_minimum_required(VERSION 2.8.3)
find_package(catkin_simple REQUIRED)
# Adding PCL lib
find_package(PCL REQUIRED)
# Setting include, lib directories and definitions
include_directories(${PCL_INCLUDE_DIRS})
link_directories(${PCL_LIBRARY_DIRS} )
add_definitions(${PCL_DEFINITIONS} )
catkin_simple(ALL_DEPS_REQUIRED)
set(CMAKE_BUILD_TYPE RelWithDebInfo) # Release, RelWithDebInfo
set(CMAKE_CXX_FLAGS "-O3 -fopenmp -std=c++11 ${CMAKE_CXX_FLAGS}")
## Generate dynamic reconfigure parameters in the 'cfg' folder
##generate_dynamic_reconfigure_options(
## cfg/EMVSCfg.cfg
##)
set(HEADERS
include/mapper_emvs/mapper_emvs.hpp
include/mapper_emvs/data_loading.hpp
include/mapper_emvs/depth_vector.hpp
include/mapper_emvs/trajectory.hpp
include/mapper_emvs/geometry_utils.hpp
include/mapper_emvs/median_filtering.hpp
)
set(SOURCES
src/mapper_emvs.cpp
src/data_loading.cpp
src/median_filtering.cpp
)
option(DEFINE_USE_INVERSE_DEPTH "Use linear spacing in inverse depth (if OFF, will use linear spacing in depth)" ON)
if(DEFINE_USE_INVERSE_DEPTH)
add_definitions(-DUSE_INVERSE_DEPTH)
endif(DEFINE_USE_INVERSE_DEPTH)
cs_add_library(${PROJECT_NAME} ${SOURCES} ${HEADERS})
# Executables
################################################################################
cs_add_executable(run_emvs src/main.cpp)
target_link_libraries(run_emvs ${PROJECT_NAME} ${PCL_LIBRARIES})
cs_add_executable(realtime_emvs src/realtime.cpp)
add_dependencies(realtime_emvs ${PROJECT_NAME}_gencfg)
target_link_libraries(realtime_emvs ${PROJECT_NAME} ${PCL_LIBRARIES})
################################################################################
cs_install()
cs_export()
Note: Hope you installed PCL lib. Besides,
I added ${PCL_LIBRARIES} into target_link_libraries. I hope it will work this way, if you are getting some errors, try adding ${PCL_LIBRARIES} into cs_add_library(${PROJECT_NAME} ${SOURCES} ${HEADERS} ${PCL_LIBRARIES}). Please let us know if get errors after applying these changes.

catkin package library link to the openCV library

I have been losing my head over this for some time now. So I need to use the opencv in a ros melodic package built by the catkin on the Ubuntu 18.04. The idea is to make a package which is actually just a library and this library using all the regular ros packages (image_transport, cv_bridge, roscpp, rospy, std_msgs, genmsg, tf, actionlib_msgs, actionlib ).
Just to let you know, I have 2 opencv installed, the openCV 3.2 in the usr/share and the openCV 4.3 in the usr/local/share, that is why I have specifically set the openCV_DIR to point to the 3.2 version.
I have tried to add message to the CMakeList.txt to print out the opencv_version, opencv_include_dir and opencv_libs and the version is 3.2.0, include_dirs is /usr/include;/usr/include/opencv and libs are opencv_calib3d;opencv_core;opencv_features2d;opencv_flann;opencv_highgui;opencv_imgcodecs;opencv_imgproc;opencv_ml;opencv_objdetect;opencv_photo;opencv_shape;opencv_stitching;opencv_superres;opencv_video;opencv_videoio;opencv_videostab;opencv_viz;opencv_aruco;opencv_bgsegm;opencv_bioinspired;opencv_ccalib;opencv_datasets;opencv_dpm;opencv_face;opencv_freetype;opencv_fuzzy;opencv_hdf;opencv_line_descriptor;opencv_optflow;opencv_phase_unwrapping;opencv_plot;opencv_reg;opencv_rgbd;opencv_saliency;opencv_stereo;opencv_structured_light;opencv_surface_matching;opencv_text;opencv_ximgproc;opencv_xobjdetect;opencv_xphoto
in my pkg_library CMakeList.txt I have this:
cmake_minimum_required(VERSION 2.8.3)
project(pkg_libraries)
## Compile as C++11, supported in ROS Kinetic and newer
# add_compile_options(-std=c++11)
set( OpenCV_DIR "/usr/share/OpenCV/" )
## Find catkin macros and libraries
## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)
## is used, also find other catkin packages
find_package(
catkin REQUIRED COMPONENTS
roscpp
rospy
std_msgs
genmsg
tf
actionlib_msgs
actionlib
sensor_msgs
cv_bridge
image_transport
message_generation
)
find_package(
OpenCV REQUIRED
)
catkin_package(
INCLUDE_DIRS include
LIBRARIES pkg_libraries
CATKIN_DEPENDS roscpp rospy std_msgs tf actionlib actionlib_msgs cv_bridge
)
include_directories(
include
${catkin_INCLUDE_DIRS}
${OpenCV_INCLUDE_DIRS}
)
add_library(${PROJECT_NAME}
src/imageSaver.cpp
)
target_link_libraries( ${PROJECT_NAME} ${catkin_LIBRARIES} ${OpenCV_LIBS} )
install(
TARGETS ${PROJECT_NAME}
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
)
install(
DIRECTORY include/${PROJECT_NAME}/
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
)
the compilation of the pkg_libraries with the catkin_build looks just fine, but later when I try to do catkin_build in the another package which includes the pkg_libraries, it fails with the error:
libpkg_libraries.so: undefined reference to
`cv::imwrite(std::__cxx11::basic_string,
std::allocator > const&, cv::_InputArray const&,
std::vector > const&)'
Which I would say looks like the linker error, because I have used the cv::imwrite only in the pkg_libraries. and the package which reports the error includes only the pkg_libraries. So the pkg_libraries but it is obviously not linked properly, but it is built without errors.
What am I missing here?
Thanks
the problem was because of the pkg_libraries is built like a shared library in which I have had another .cpp and .h which were using different openCV versions (default opencv 3.2) and I think the problem happened because by loading the libpkg_libraries.so I have made a conflict between openCV version.
Anyway, now I have made separate libraries and it works as it suppose to work.
Thanks

Can't make find_package(Opencv) on opencv 3.3rc for android:

I am trying to integrate the new Opencv3.3rc tag to use OpenCV dnn module.
https://github.com/opencv/opencv/tree/3.3.0-rc
I can cross compile the OpenCV library but when I try to make the FindOpencv required I have this error:
Some (but not all) targets in this export set where already defined.
The unique target registered is cpufeatures as you can see:
Targets Defined: cpufeatures
Targets not yet defined:
libtiff;libjpeg;libwebp;libjasper;libpng;IlmImf;tegra_hal;libprotobuf;opencv_core;opencv_flann;opencv_imgproc;opencv_ml;opencv_objdetect;opencv_photo;opencv_video;opencv_dnn;opencv_imgcodecs;opencv_shape;opencv_videoio;opencv_highgui;opencv_superres;opencv_features2d;opencv_calib3d;opencv_java;opencv_stitching;opencv_videostab
As I can see in the OpenCVconfig.cmake configuration file, currently, there are two methods to find OpenCV:
this:
find_package(OpenCV REQUIRED)
or defining modules:
find_package(OpenCV REQUIRED core videoio)
But none of them works.
The error comes from this snippet OpenCVModules.cmake
# Commands may need to know the format version.
set(CMAKE_IMPORT_FILE_VERSION 1)
# Protect against multiple inclusion, which would fail when already imported targets are added once more.
set(_targetsDefined)
set(_targetsNotDefined)
set(_expectedTargets)
foreach(_expectedTarget cpufeatures libtiff libjpeg libwebp libjasper libpng IlmImf tegra_hal libprotobuf opencv_core opencv_flann opencv_imgproc opencv_ml opencv_objdetect opencv_photo opencv_video opencv_dnn opencv_imgcodecs opencv_shape opencv_videoio opencv_highgui opencv_superres opencv_features2d opencv_calib3d opencv_java opencv_stitching opencv_videostab)
list(APPEND _expectedTargets ${_expectedTarget})
if(NOT TARGET ${_expectedTarget})
list(APPEND _targetsNotDefined ${_expectedTarget})
endif()
if(TARGET ${_expectedTarget})
list(APPEND _targetsDefined ${_expectedTarget})
endif()
endforeach()
if("${_targetsDefined}" STREQUAL "${_expectedTargets}")
unset(_targetsDefined)
unset(_targetsNotDefined)
unset(_expectedTargets)
set(CMAKE_IMPORT_FILE_VERSION)
cmake_policy(POP)
return()
endif()
if(NOT "${_targetsDefined}" STREQUAL "")
message(FATAL_ERROR "Some (but not all) targets in this export set were already defined.\nTargets Defined: ${_targetsDefined}\nTargets not yet defined: ${_targetsNotDefined}\n")
endif()
Anybody knows how this could happen?
I found the answer:
I was defining the cpu-features library before, so this code was the conflicting part in the CMakelists.txt.
add_library(cpufeatures STATIC
${ANDROID_NDK}/sources/android/cpufeatures/cpu-features.c)
Removing this part, the problem was solved.

Linker can not find OpenCV libraries when using CMake

I have a copy of OpenCV2.4.0 installed in /usr/local/lib
My program compiled properly but when the linker is evoked, it gave errors such as:
/home/zhouw/moos-ivp-zhouw/trunk/src/pATRTest/mst.cpp:661: undefined reference to 'cv::_OutputArray::_OutputArray(cv::Mat const&)'
CMakeFiles/pATR.dir/mst.cpp.o:/home/zhouw/moos-ivp-zhouw/trunk/src/pATRTest/mst.cpp:675: more undefined references to `cv::_OutputArray::_OutputArray(cv::Mat const&)'
collect2: ld returned 1 exit status
make[2]: *** [../bin/pATR] Error 1
make[1]: *** [src/pATRTest/CMakeFiles/pATR.dir/all] Error 2
make: *** [all] Error 2
The strange thing is my program uses opencv intensively, if CMake has trouble finding the libraries, it should have complained a lot more undefined references than jsut a few.
I tried adding
LINK_DIRECTORIES("/usr/local/lib") in my cmake file but it didn't help.
There's another library called POCO is also installed under /usr/local/lib. My program also links to the POCO libraries, but CMake seems having no trouble finding them.
If I manually link with -L/usr/local/lib, it would link properly without error.
The CMakeLists.txt looks like this
PROJECT(pATR)
#what files are needed?
SET(SRCS
spline.hpp
utils.hpp utils.cpp
mst.hpp mst.cpp
cluster.hpp cluster.cpp
target.hpp target.cpp
detector.hpp detector.cpp
classifier.hpp classifier.cpp
atr.hpp atr.cpp
MOOSAtr.h MOOSAtr.cpp
main.cpp
)
ADD_EXECUTABLE(pATR ${SRCS})
# indicate how to link
#LINK_DIRECTORIES("/usr/local/lib")
TARGET_LINK_LIBRARIES(pATR opencv_core opencv_highgui opencv_imgproc MOOS)
INSTALL(TARGETS
pATR
RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin
)
Any idea what's going on? Many thanks!
If you have CMake 2.8, I recommend using find_package(OpenCV) to load the libraries.
There is an example at http://docs.opencv.org/doc/tutorials/introduction/linux_gcc_cmake/linux_gcc_cmake.html
The CMake file:
cmake_minimum_required(VERSION 2.8)
project( DisplayImage )
find_package( OpenCV REQUIRED )
add_executable( DisplayImage DisplayImage.cpp )
target_link_libraries( DisplayImage ${OpenCV_LIBS} )
You're after:
find_package(OPENCV COMPONENTS core imgproc highgui REQUIRED)
From the docs:
Packages with components
Some libraries are not monolithic, but come with one or more dependent
libraries or components. A notable example for this is the Qt library,
which ships (among others) with the components QtOpenGL and QtXml. To
use both of these components, use the following the find_package
command:
find_package(Qt COMPONENTS QtOpenGL QtXml REQUIRED)
also, for more info you may check out the following link.
https://gitlab.kitware.com/cmake/community/wikis/doc/tutorials/How-To-Find-Libraries
I am not sure if it makes sense that CMake can't find the linking libraries. CMake finds your dependencies and generates the Makefile, but it doesn't actually compile and link for you.
Your error are not from CMake, right? They are from make.
I always link manually with this
g++ -o myopencvapp `pkg-config --cflags --libs opencv` myopencvapp.cpp`
when invoking g++.

cmake and libpthread

I'm running RHEL 5.1 and use gcc.
How I tell cmake to add -pthread to compilation and linking?
#Manuel was part way there. You can add the compiler option as well, like this:
If you have CMake 3.1.0+, this becomes even easier:
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app PRIVATE Threads::Threads)
If you are using CMake 2.8.12+, you can simplify this to:
find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
target_compile_options(my_app PUBLIC "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()
Older CMake versions may require:
find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
set_property(TARGET my_app PROPERTY COMPILE_OPTIONS "-pthread")
set_property(TARGET my_app PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()
If you want to use one of the first two methods with CMake 3.1+, you will need set(THREADS_PREFER_PTHREAD_FLAG ON) there too.
The following should be clean (using find_package) and work (the find module is called FindThreads):
cmake_minimum_required (VERSION 2.6)
find_package (Threads)
add_executable (myapp main.cpp ...)
target_link_libraries (myapp ${CMAKE_THREAD_LIBS_INIT})
Here is the right anwser:
ADD_EXECUTABLE(your_executable ${source_files})
TARGET_LINK_LIBRARIES( your_executable
pthread
)
equivalent to
-lpthread
target_compile_options solution above is wrong, it won't link the library.
Use:
SET(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -pthread")
OR
target_link_libraries(XXX PUBLIC pthread)
OR
set_target_properties(XXX PROPERTIES LINK_LIBRARIES -pthread)

Resources