Issue
I'm quite new to CMake, but I want to build a test .cpp
file that includes OpenCV and shows me an image. I have built OpenCV in the path /usr/local
and I have here folder with opencv.hpp file - /usr/local/include/opencv4/opencv2/opencv.hpp
. Here is my CMakeLists.txt file:
cmake_minimum_required(VERSION 3.0)
project(cpp_proj)
find_package(OpenCV REQUIRED)
add_executable(cpp_proj opencv_cpp.cpp)
include_directories(${OPENCV4_INCLUDES})
target_link_libraries(cpp_proj )
I opened ~./bashrc
and added there lines:
export OPENCV4_INCLUDES=/usr/local/include/
export OPENCV4_LIBRARIES=/usr/local/lib/
export PATH=$PATH:$OPENCV4_LIBRARIES
export PATH=$PATH:$OPENCV4_INCLUDES
When I run cmake
in bash - everything is ok and even find_package finds OpenCV. But when I'm trying to run make
it gives me a error:
pi@raspberrypi:~/Desktop/cpp_proj/build $ cmake ..
-- Configuring done
-- Generating done
-- Build files have been written to: /home/pi/Desktop/cpp_proj/build
pi@raspberrypi:~/Desktop/cpp_proj/build $ make
[ 50%] Building CXX object CMakeFiles/cpp_proj.dir/opencv_cpp.cpp.o
/home/pi/Desktop/cpp_proj/opencv_cpp.cpp:1:10: fatal error: opencv2/opencv.hpp: No such file or directory
#include <opencv2/opencv.hpp>
^~~~~~~~~~~~~~~~~~~~
compilation terminated.
make[2]: *** [CMakeFiles/cpp_proj.dir/build.make:63: CMakeFiles/cpp_proj.dir/opencv_cpp.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/cpp_proj.dir/all] Error 2
make: *** [Makefile:84: all] Error 2
I found questions with the same problem, but they didn't help me. What I am doing wrong? What could be the reason of this? Thanks!
Solution
In order to use a library you must specify the include directory as well as the libs.
With find_package (in module mode), in your case it should populate the variables OpenCV_INCLUDE_DIRS and OpenCV_LIBS for you to use.
So I recommend to add / alter your code to add the include directory & link the library (such as below)
target_include_directories(${CMAKE_PROJECT_NAME} public ${OpenCV_INCLUDE_DIRS})
target_link_libraries(${CMAKE_PROJECT_NAME} public ${OpenCV_LIBS})
I don't believe you ever need to touch ~./bashrc when using find_package
Answered By - Hugo