CMake - 使用 FetchContent 下载后如何构建 Boost?

Een*_*oku 7 c++ boost compilation repository cmake

我的目标是在找不到 Boost 存储库时下载它,然后以默认方式(即使用boostrapb2工具)构建它。

我知道,我可以这样下载:

include(FetchContent)
FetchContent_Declare(
    Boost
    PREFIX external_dependencies/boost
    GIT_REPOSITORY https://github.com/boostorg/boost.git
    GIT_SUBMODULES libs/system libs/serialization libs/random 
                   libs/function libs/config libs/headers libs/assert libs/core libs/integer 
                   libs/type_traits libs/mpl libs/throw_exception libs/preprocessor libs/utility 
                   libs/static_assert libs/smart_ptr libs/predef libs/move libs/io libs/iterator 
                   libs/detail libs/spirit libs/optional libs/type_index libs/container_hash
                   libs/array libs/bind
                   tools/build tools/boost_install
)   

FetchContent_GetProperties(Boost)
FetchContent_Populate(Boost)
Run Code Online (Sandbox Code Playgroud)

但是我现在如何正确构建它?我想运行以下命令:

./bootstrap.sh
./b2 headers
./b2 -q cxxflags="-fPIC" --layout=system variant=${BUILD_TYPE} link=${LINK_TYPE} address-model=64 --with-system --with-serialization --with-random
Run Code Online (Sandbox Code Playgroud)

我正在考虑add_custom_target()add_custom_command()函数,但我不确定这是否是推荐的方法。

Vic*_*gue 2

add_custom_target可能更好,因为它声明了一个方便依赖的目标,使用add_dependencies.

每个命令可能需要一个目标,这很快就会变得烦人。因此,我会尝试(我没有)编写一个执行构建的脚本,我们称之为build-boost.sh

#!/bin/bash
# This is meant to be run from the source directory of Boost.
./bootstrap.sh
./b2 headers
./b2 -q cxxflags="-fPIC" --layout=system variant=$2 link=$3 address-model=64 --with-system --with-serialization --with-random
./b2 install --prefix=$4
Run Code Online (Sandbox Code Playgroud)

在您的 CMake 代码中,您可以这样调用它:

add_custom_target(
  build-boost
  COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/build-boost.sh ${BUILD_TYPE} ${LINK_TYPE} ${CMAKE_CURRENT_BINARY_DIR}/external_dependencies/boost-installation
  WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/external_dependencies/boost
)
Run Code Online (Sandbox Code Playgroud)

之后,你还没有完成。您仍然应该导出通常导出的所有变量FindBoost,并提前创建所有预期的目录(在 下${CMAKE_CURRENT_BINARY_DIR}/external_dependencies/boost-installation),因为在配置时二进制文件和标头尚不存在。

如果您完成了这项工作,请告知社区,因为这可能会有所帮助。