How to build cmake ExternalProject while configurating main one?

You may use cmake call within execute_process for configure and build CMake project, which contains ExternalProject:

other_project/CMakeLists.txt:

project(other_project)
include(ExternalProject)

ExternalProject_Add(<project_name> <options...>)

CMakeLists.txt:

# Configure external project
execute_process(
    COMMAND ${CMAKE_COMMAND} ${CMAKE_SOURCE_DIR}/other_project
    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/other_project
)

# Build external project
execute_process(
    COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR}/other_project
)

Such a way other_project will be configured and built in directory ${CMAKE_BINARY_DIR}/other_project. If you do not disable installation in ExternalProject_Add call, then it will performed when building other_project.

Normally, you want some options to ExternalProject, like SOURCE_DIR, BINARY_DIR, INSTALL_DIR, to be deduced from variables in the main project. You have two ways for achive that:

  1. Create CMakeLists.txt for other_project with configure_file, called from main project (before execute_process command).

  2. Pass variables from main project as -D parameters to ${CMAKE_COMMAND}.


Having separated execute_process calls for sequential COMMANDS is important. Otherwise, if use single execute_process with several COMMANDS, these commands will be just “piped” (executed concurrently but with output of the first command being treated as input for the second).

Leave a Comment