Skip to content

Instantly share code, notes, and snippets.

@realoriginal
Last active November 3, 2025 04:35
Show Gist options
  • Select an option

  • Save realoriginal/e7fe0bb8d60d950c003b35be19bb2b42 to your computer and use it in GitHub Desktop.

Select an option

Save realoriginal/e7fe0bb8d60d950c003b35be19bb2b42 to your computer and use it in GitHub Desktop.
include( FetchContent )
#
# Usage:
# fetch_build_install(
# <name>
# URL <url> | GIT_REPOSITORY <repo> [GIT_TAG <tag>]
# INSTALL_DIR <path>
# [SUBDIR] <relative-path>
# [CMAKE_ARGS ...]
# )
#
function( fetch_build_install NAME )
# Force the name to be compatible with FetchContent
string(TOLOWER ${NAME} NAME)
set(options "")
set(oneValueArgs URL GIT_REPOSITORY GIT_TAG INSTALL_DIR SUBDIR)
set(multiValueArgs CMAKE_ARGS)
cmake_parse_arguments(FBI "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
# Was a URL not specified?
if ( NOT FBI_URL AND NOT FBI_GIT_REPOSITORY )
message( FATAL_ERROR "fetch_build_install: must specify either URL or GIT_REPOSITORY")
endif()
# Was an install directory not specified?
if ( NOT FBI_INSTALL_DIR )
message( FATAL_ERROR "fetch_build_install: must specify a install directory" )
endif()
# Fetch the package
if ( FBI_URL )
FetchContent_Declare(${NAME} URL ${FBI_URL})
else()
FetchContent_Declare(${NAME} GIT_REPOSITORY ${FBI_GIT_REPOSITORY} GIT_TAG ${FBI_GIT_TAG})
endif()
# Get the properties of the package
FetchContent_GetProperties(${NAME})
# Have we been populated yet?
if ( NOT ${NAME}_POPULATED )
# Populate the content
FetchContent_Populate(${NAME})
# Was a sub directory specified?
if(FBI_SUBDIR)
set(SOURCE_DIR "${${NAME}_SOURCE_DIR}/${FBI_SUBDIR}")
else()
set(SOURCE_DIR "${${NAME}_SOURCE_DIR}")
endif()
# Fetch the original command line arguments
message( STATUS "Configuring ${NAME} with args: ${FBI_CMAKE_ARGS}" )
# Start the configuration process
execute_process(
COMMAND ${CMAKE_COMMAND} -G ${CMAKE_GENERATOR} -S ${SOURCE_DIR} -B ${${NAME}_BINARY_DIR} ${FBI_CMAKE_ARGS} -DCMAKE_INSTALL_PREFIX=${FBI_INSTALL_DIR}
WORKING_DIRECTORY ${${NAME}_SOURCE_DIR}
RESULT_VARIABLE RETURN_CODE
ERROR_VARIABLE ERROR_MESSAGE
)
if ( NOT ${RETURN_CODE} EQUAL 0 )
message( FATAL_ERROR "${RETURN_CODE}: ${ERROR_MESSAGE}")
endif()
# Start the build process
execute_process(
COMMAND ${CMAKE_COMMAND} --build ${${NAME}_BINARY_DIR} --target install
RESULT_VARIABLE RETURN_CODE
ERROR_VARIABLE ERROR_MESSAGE
)
if ( NOT ${RETURN_CODE} EQUAL 0 )
message( FATAL_ERROR "${RETURN_CODE}: ${ERROR_MESSAGE}")
endif()
# Set the install directory for this package
set(${NAME}_INSTALL_DIR ${FBI_INSTALL_DIR} PARENT_SCOPE)
endif()
endfunction()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment