eager2learn
eager2learn

Reputation: 1488

CMake file in subdirectory cannot access external library

My project structure looks like this:

Project
  | Dependency
      functions.cpp
      functions.h
  | DisplayImage.cpp

I want to use opencv in functions.cpp. It works when I use opencv functions in DisplayImage, but when I include opencv2/imgproc.hpp in functions.h I get a 'file not found error'.

My CMakeLists looks like this in the root:

cmake_minimum_required(VERSION 3.10)

project(DisplayImage)

set("OpenCV_DIR" "~/opencv/build")
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(OpenCV REQUIRED)

add_subdirectory(Dependency)

add_executable(DisplayImage DisplayImage.cpp)

target_link_libraries(DisplayImage ${OpenCV_LIBS})

include_directories("${CMAKE_SOURCE_DIR}/Dependency")
include_directories("~/CppLibraries/eigen-3.3.7/Eigen")

and the CMakeLists.txt file in the Dependency directory contains:

add_library(Dependency functions.cpp functions.h)

Why can opencv2/imgproc.hpp not be found in functions.h?

This is the error message I get:

$ cmake --build .
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/bn/Documents/C++/opencv_playground/build
Scanning dependencies of target DisplayImage
[ 25%] Building CXX object CMakeFiles/DisplayImage.dir/DisplayImage.cpp.o
[ 50%] Linking CXX executable DisplayImage
[ 50%] Built target DisplayImage
[ 75%] Building CXX object Dependency/CMakeFiles/Dependency.dir/functions.cpp.o
In file included from /Users/bn/Documents/C++/opencv_playground/Dependency/functions.cpp:1:
/Users/bn/Documents/C++/opencv_playground/Dependency/functions.h:1:10: fatal error: 'opencv2/imgproc.hpp'
      file not found
#include <opencv2/imgproc.hpp>
         ^~~~~~~~~~~~~~~~~~~~~
1 error generated.
make[2]: *** [Dependency/CMakeFiles/Dependency.dir/functions.cpp.o] Error 1
make[1]: *** [Dependency/CMakeFiles/Dependency.dir/all] Error 2
make: *** [all] Error 2

Upvotes: 0

Views: 929

Answers (2)

Ying Zhou
Ying Zhou

Reputation: 56

For debugging purpose you can add following lines in your CMakeLists.txt after "find_package( OpenCV REQUIRED )"

message(STATUS "cv libs: ${OpenCV_LIBS}")
message(STATUS "include_path: ${OpenCV_INCLUDE_DIRS}")

when you do "cmake .", in the terminal, it will prints out all opencv libs and include paths.

Upvotes: 1

eager2learn
eager2learn

Reputation: 1488

In the CMakeLists.txt file in the Dependency subdirectory, I needed to include target_link_libraries(Dependency PUBLIC ${OpenCV_LIBS}), so the CMakeLists file looks like:

add_library(Dependency functions.cpp functions.h)
target_link_libraries(Dependency PUBLIC ${OpenCV_LIBS})

Upvotes: 0

Related Questions