在GitHub Actions中构建含pybind11的Python包时CMake无法找到Boost
解决CMake在GitHub Actions中找不到Boost的问题
核心问题原因
cibuildwheel会在隔离的构建环境中执行编译,你在主机环境安装的Boost默认不会被这个隔离环境检测到;macOS下brew安装的Boost路径刚好在CMake默认搜索路径内,所以能正常工作,但Windows和Linux需要显式指定Boost位置。
解决方案步骤
1. 修改GitHub Actions Workflow,传递Boost路径给cibuildwheel
MarkusJx/install-boost动作会输出BOOST_ROOT变量,需要将这个变量注入到cibuildwheel的构建环境中,让CMake能定位到Boost。修改Build wheels步骤的环境变量:
- name: Build wheels uses: pypa/cibuildwheel@v2.11.4 env: CIBW_BUILD: cp${{ matrix.python }}-* # CIBW_ARCHS_MACOS: x86_64 arm64 CIBW_ARCHS_MACOS: x86_64 CIBW_ARCHS_LINUX: auto aarch64 # 传递Boost路径到构建环境 CIBW_ENVIRONMENT_WINDOWS: "BOOST_ROOT=${{ steps.install-boost-windows.outputs.BOOST_ROOT }}" CIBW_ENVIRONMENT_LINUX: "BOOST_ROOT=${{ steps.install-boost-linux.outputs.BOOST_ROOT }}"
2. 优化CMakeLists.txt,去掉硬编码路径
移除硬编码的系统路径,完全依赖CMake的FindBoost模块自动处理路径:
cmake_minimum_required(VERSION 3.13) project(boost_example) if(APPLE) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -stdlib=libc++") endif(APPLE) add_subdirectory(pybind11) # 显式读取环境变量中的Boost根目录 if(DEFINED ENV{BOOST_ROOT}) set(BOOST_ROOT $ENV{BOOST_ROOT}) endif() find_package(Boost COMPONENTS chrono thread serialization REQUIRED) pybind11_add_module(_boost_example src/boost_example/_boost_example/main.cpp) target_include_directories(_boost_example PRIVATE ${CMAKE_SOURCE_DIR}/include ${USER_INCLUDE_PATH}/database ${USER_INCLUDE_PATH} ) # Boost::*目标已包含链接路径,无需手动设置link_directories target_link_libraries(_boost_example PRIVATE Boost::chrono Boost::thread Boost::serialization )
额外说明
- 不需要更换Boost安装方式,
MarkusJx/install-boost是可靠的跨平台安装方案,关键是要把安装后的路径传递给隔离的构建环境。 - CMake的
FindBoost模块会优先使用BOOST_ROOT环境变量来定位Boost,注入该变量即可解决找不到的问题。
内容的提问来源于stack exchange,提问作者marcm
相关产品推荐
相关产品推荐

