Visual Studio 2022 + vcpkg配置Ceres-Solver编译失败求助
解决VS2022 + vcpkg下Ceres-Solver编译错误(glog引用失败等问题)
一、重新正确安装Ceres-Solver及依赖
- 打开vcpkg所在目录的终端,先更新vcpkg到最新版:
git pull .\bootstrap-vcpkg.bat - 安装对应平台的Ceres-Solver(以x64为例,必须和项目平台完全一致):
若需要稀疏矩阵、多线程等扩展特性,可安装带功能集的版本:vcpkg install ceres:x64-windowsvcpkg install ceres[suitesparse,openmp]:x64-windows - 执行vcpkg与VS的集成命令,确保VS能自动识别包路径:
执行成功会提示"Applied user-wide integration for this vcpkg root.",之后必须重启VS。vcpkg integrate install
二、VS项目核心配置
- 平台匹配:右键项目→属性→配置管理器,确认活动解决方案平台为
x64(禁止x86与x64混合使用,否则依赖完全不匹配)。 - 编译器标准:项目属性→C/C→语言→C标准,设置为
ISO C++17标准(/std:c++17)(Ceres依赖C++17及以上特性)。 - 预处理器定义:如果使用静态链接,需在项目属性→C/C++→预处理器→预处理器定义中添加
CERES_STATIC_LIBRARY;动态链接无需额外添加。 - 运行库匹配:静态链接时,将C/C++→代码生成→运行库设置为
多线程(/MT)(Debug模式下为多线程调试(/MTd));动态链接则选多线程DLL(/MD)(Debug模式为多线程调试DLL(/MDd))。
三、代码规范检查
确保官方HelloWorld代码的头文件引用和初始化步骤正确(关键是glog的初始化不能漏):
#include <ceres/ceres.h> #include <glog/logging.h> struct CostFunctor { template <typename T> bool operator()(const T* const x, T* residual) const { residual[0] = T(10.0) - x[0]; return true; } }; int main(int argc, char** argv) { // 必须初始化glog,否则会触发日志相关编译/运行错误 google::InitGoogleLogging(argv[0]); double initial_x = 5.0; double x = initial_x; ceres::Problem problem; ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<CostFunctor, 1, 1>(new CostFunctor); problem.AddResidualBlock(cost_function, nullptr, &x); ceres::Solver::Options options; options.minimizer_progress_to_stdout = true; ceres::Solver::Summary summary; ceres::Solve(options, &problem, &summary); std::cout << summary.BriefReport() << "\n"; std::cout << "x : " << initial_x << " -> " << x << "\n"; return 0; }
注意:不要手动添加glog或Eigen的头文件/库路径,vcpkg会自动管理所有依赖项,手动添加反而会引发版本冲突。
四、最后排查步骤
- 如果仍有
glog/logging.h找不到的错误,检查vcpkg安装目录下installed\x64-windows\include是否存在glog文件夹,若不存在则重新运行安装命令。 - 清理项目的中间文件:右键项目→清理,然后重新生成解决方案。
- 确保没有手动添加过其他版本的glog、Eigen或Ceres到项目配置中,全部依赖由vcpkg提供。
内容的提问来源于stack exchange,提问作者Hzine
相关产品推荐
相关产品推荐

