Cmake:如何 link 多个库?

Cmake: How to link multiple libraries?

我正在使用 CMake 来定义 C++ 可执行文件的编译。目标是使用 2 个第三方库,Open3D 和 OpenCV。我可以用 target_link_libraries 包含两者之一,但包含这两个结果会导致找不到 OpenCV 函数。

这是我现在的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

有了这个CMakeList.txt,我就可以成功使用OpenCV的函数了。通过使用注释掉的Open3D target_link_libraries,我可以成功使用Open3D。当取消注释 target_link_libraries 时,无论 find_packagetarget_link_libraries 的顺序如何,它都找不到 OpenCV 功能。如果我将两者都包含在一个 target_link_libraries(ORB_SLAM ${OpenCV_LIBS} ${Open3D_LIBRARIES}) 中,甚至会出现相同的错误。 CMake 3.16.3和3.21.3出现同样的错误。

错误如下:

/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)'

求代码

#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);  
}

似乎 Open3D::Open3D 优先于 opencv_calib3d;opencv_core;...。是什么原因造成的,我该如何解决?这可能是由于 Open3D 的“::”与 OpenCV 的小写符号之间存在差异?

编辑:如果有任何用处,这里是所有 CMake 变量的转储 https://textuploader.com/t5dvl/raw

请原谅我的经验不足。我在 CMake 文档和 Whosebug 问题中搜索了线索,但到目前为止我什么也没找到。

通过找到这个 Github 问题解决了问题:https://github.com/isl-org/Open3D/issues/2286
通过在构建 Open3D 时使用特定的构建标志,可以使用 target_link_libraries(ORB_SLAM ${OpenCV_LIBS} ${Open3D_LIBRARIES}) 命令正确并同时链接这些库。

构建命令如下;

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