Add Custom Command

Kent - September 26, 2023

Add custom command in CMake can be used to copy assets and runtime dependencies into the build folder for easier debugging.

The one thing to remember when you’re about to copy assets/dependencies into the build folder, is that it should be done at the BUILD stage, and not the CONFIGURE stage of CMake.

If you find your self doing generator expressions during the configure stage of CMake, you’re doing something wrong.

# Wrong
configure_file(
    ${CMAKE_SOURCE_DIR}/bin/runtime-lib.dll
    ${CMAKE_BINARY_DIR}/$<CONFIG>/ 
    #             error ^^^^^^^^^
    COPYONLY)

This generator expression will not be executed, since this is evaluated during configure. Generator expressions are only evaluated during build.

Use add_custom_command to copy over runtime dependencies to the build folder.

Given the following CMakeLists.txt;

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
cmake_minimum_required(VERSION 3.27.0)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_RUN)

project(add-custom-command)
add_executable(hello add-custom-command.cpp)

add_custom_command(
    TARGET hello 
    COMMAND ${CMAKE_COMMAND} -E copy_if_different
    ${CMAKE_SOURCE_DIR}/dependency.txt ${CMAKE_BINARY_DIR}/$<CONFIG>/
    )

Build with:

cmake -S. -Bbuild

See Also

Comments

Any comments? Create a new discussion on GitHub.
There used to be an inline comment form here, but it was removed.