CMakeLists.txt很重要,以下问题不分先后难易,遇到则记录
找不到三方库
- 问题背景: 本地通过源码安装完 g2o 后,find_package 找不到该库,报错如下
CMake Error at CMakeLists.txt:12 (find_package):
By not providing "FindG2O.cmake" in CMAKE_MODULE_PATH this project has
asked CMake to find a package configuration file provided by "G2O", but
CMake did not find one.
Could not find a package configuration file provided by "G2O" with any of
the following names:
G2OConfig.cmake
g2o-config.cmake
Add the installation prefix of "G2O" to CMAKE_PREFIX_PATH or set "G2O_DIR"
to a directory containing one of the above files. If "G2O" provides a
separate development package or SDK, be sure it has been installed.
- 解决方法: 在 find_package(G2O REQUIRED) 前加入
# -- g2o源码下载路径
list(APPEND CMAKE_MODULE_PATH /home/xxx/3rdparty/g2o/cmake_modules)
# -- g2o编译安装位置
set(G2O_ROOT /usr/local/include/g2o)
- 可能引入的问题:
CMake Warning (dev) at CMakeLists.txt:12 (find_package):
Policy CMP0074 is not set: find_package uses <PackageName>_ROOT variables.
Run "cmake --help-policy CMP0074" for policy details. Use the cmake_policy
command to set the policy and suppress this warning.
CMake variable G2O_ROOT is set to:
/usr/local/include/g2o
For compatibility, CMake is ignoring the variable.
This warning is for project developers. Use -Wno-dev to suppress it.
- 可以的解决方法: 在 CMakeLists.txt 中加入
cmake_policy(SET CMP0074 NEW)
编库用库
- 问题背景: 想把一些常用的函数抽出来编成库方便调用,以 slambook2 的 ch7 为例,在 ch7 目录下创建 ch7_utils 文件夹,主要目录结构如下,将 find_feature_matches 函数打包入库
ch7
├── ch7_utils
│ ├── ch7_utils.h
│ ├── ch7_utils.cpp
│ └── CMakeLists.txt
├── orb_cv.cpp
├── triangulation.cpp
└── CMakeLists.txt
如上,find_feature_matches 函数在 orb_cv.cpp 和 triangulation.cpp 均有使用,为了懒惰可将其写入库中,依习惯将工具函数打包放入对应 _utils 文件夹中 「当然也可以写.hpp文件供二者调用,更简单」
- 解决方法: 贴代码了直接
ch7_utils.h
#include <opencv2/core/core.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
void find_feature_matches(const cv::Mat &img_1, const cv::Mat &img_2, std::vector<cv::KeyPoint> &keypoints_1,
std::vector<cv::KeyPoint> &keypoints_2, std::vector<cv::DMatch> &matches);
ch7_utils.cpp
#include "ch7_utils.h"
void find_feature_matches(const cv::Mat &img_1, const cv::Mat &img_2, std::vector<cv::KeyPoint> &keypoints_1,
std::vector<cv::KeyPoint> &keypoints_2, std::vector<cv::DMatch> &matches) {
... // -- 函数内部省略
}
CMakeList.txt「ch7_utils」
set(module_name ch7_utils)
set(long_name slam_${module_name})
set(${module_name}_SOURCE_FILES
ch7_utils.cpp
)
add_library(${long_name} SHARED ${${module_name}_SOURCE_FILES})
# -- 没必要按上面这么写,只是代码风格以及工程管理习惯
# -- 简单点的话一个add_library即可,如下
add_library(slam_ch7_utils SHARED ch7_utils.cpp)
CMakeList.txt「ch7」
include_directories(
...
./ch7_utils/
)
add_subdirectory(ch7_utils)
add_executable(triangulation triangulation.cpp)
target_link_libraries(triangulation
...
slam_ch7_utils
)