'CMake - how to build Boost after downloading it with FetchContent?

My goal is to download the Boost repository if it isn't found and then build it the default way, i.e. using boostrap and b2 tools.

I know, I can download it like this:

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)

But how can I build it now correctly? I'd like to run following commands:

./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

I'm thinking about add_custom_target() and add_custom_command() functions, but I'm not sure, if it's the recommended way to do this.



Solution 1:[1]

add_custom_target is probably better because it is declaring a target that is convenient to depend on, using add_dependencies.

You may need one target per command, and that becomes quickly annoying. So instead I would try (I did not) writing a script performing the build, let's call it 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

In your CMake code, you would be calling it this way:

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
)

After that, you are not done yet. You should still export all the variables FindBoost usually exports, and create all expected directories in advance (under ${CMAKE_CURRENT_BINARY_DIR}/external_dependencies/boost-installation), since at configuration time the binaries and headers are not present yet.

If you complete this work, please let the community know, since this can be helpful.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Victor Paléologue