Cmake: How to link multiple libraries?

Viewed 302

I am using CMake to define the compilation of a C++ executable. The goal is to use 2 third-party libraries, Open3D and OpenCV. I am able to include one of the two with target_link_libraries, but including both results in OpenCV functions not being found.

This is my current CMakeLists.txt

minimum_required(VERSION 3.20)
project(ORB_SLAM)

find_package(Open3D REQUIRED)
find_package(OpenCV REQUIRED)

set(CMAKE_CXX_STANDARD 20)
add_executable(ORB_SLAM src/main.cpp)

#target_link_libraries(ORB_SLAM ${Open3D_LIBRARIES})
target_link_libraries(ORB_SLAM ${OpenCV_LIBS})

# When printed, ${Open3D_LIBRARIES} = Open3D::Open3D
#               ${OpenCV_LIBS} = opencv_calib3d;opencv_core;...many more..;opencv_xphoto

With this CMakeList.txt, I can successfully use OpenCV functions. By using the commented out Open3D target_link_libraries, I can successfully use Open3D. When uncommenting both target_link_libraries, it fails to find OpenCV functionality, regardless of the order of the find_package and target_link_libraries. The same error even occurs if I include both in a single target_link_libraries(ORB_SLAM ${OpenCV_LIBS} ${Open3D_LIBRARIES}). The same error occurs for CMake 3.16.3 and 3.21.3.

The error is as follows:

/usr/bin/ld: CMakeFiles/ORB_SLAM.dir/src/main.cpp.o: in function `main':
/home/m/CLionProjects/ORB_SLAM/src/main.cpp:20: undefined reference to `cv::VideoCapture::VideoCapture(std::string const&, int)'

For the code

#include <opencv2/opencv.hpp>
#include <opencv2/videoio.hpp>
//#include <open3d/Open3D.h>

int main() {
    cv::VideoCapture cap("/home/.../scene.mp4");
    //auto sphere = open3d::geometry::TriangleMesh::CreateSphere(1.0);  
}

It seems as though Open3D::Open3D takes precedence over opencv_calib3d;opencv_core;.... What is causing this and how can I fix it? Is this perhaps due to the discrepancy in Open3D's "::" vs OpenCV's lowercase notation?

Edit: Here is a dump of all CMake variables if it is of any use https://textuploader.com/t5dvl/raw

Excuse my inexperience. I have searched through CMake documentation and Stackoverflow questions for a lead, but so far I have found nothing.

1 Answers

The problem was solved by finding this Github issue: https://github.com/isl-org/Open3D/issues/2286
By using specific build flags when building Open3D, the libraries could both be linked correctly and simultaneously with the target_link_libraries(ORB_SLAM ${OpenCV_LIBS} ${Open3D_LIBRARIES}) command.

The build commands were as follows;

git clone --recursive https://github.com/intel-isl/Open3D
cd Open3D && source util/scripts/install-deps-ubuntu.sh
mkdir build && cd build
cmake -DBUILD_EIGEN3=ON -DBUILD_GLEW=ON -DBUILD_GLFW=ON -DBUILD_JSONCPP=ON -DBUILD_PNG=ON -DGLIBCXX_USE_CXX11_ABI=ON -DPYTHON_EXECUTABLE=/usr/bin/python -DBUILD_UNIT_TESTS=ON ..
make -j4
sudo make install
Related