Friday, September 2, 2022

[SOLVED] Get full target filename without generator expressions

Issue

I am trying to use configure_file in order to set-up a run-script for my binary. This run-script shall reference the built binary and in order for that to work, the script obviously has to know the final name of the binary.

In order to make this as generic as possible, I was thinking to retrieve the binary's name within cmake and then use configure_file to insert that name into my run-script.

However, to my understanding configure_file has to be run at configure-time and thus using a generator expression as $<TARGET_FILE:my_binary> won't work as those are evaluated at build-time.

I am aware of the OUTPUT_NAME target property, but this name does not include potential prefixes and suffixes.

Thus, my question would be: How to obtain the full name of the final binary at configure-time so that I can store that name in a variable inside cmake and thus use this variable during a configure_file call in order to insert that name into my run-script?


Solution

In general there is no such functionality available. However you could add a custom target to your project for running the script or for generating the script as part of the build process.

Alternatively depending on what you're trying to set up here using add_test could be an option. CMake automatically replaces the mention of a executable cmake target name with the path to the file built when generating the actual test command. (Note: You can use ctest to run those tests.)

# option 1
add_custom_command(OUTPUT /path/to/script/file
    COMMAND /path/to/generator --executable-path $<TARGET_FILE:my_target> -o /path/to/script/file
    DEPENDS /path/to/generator
)
add_custom_target(generate_run_scripts ALL DEPENDS /path/to/script/file)
# (generate the scripts with cmake --build ... --target generate_run_scripts)

# option 2
add_custom_target(run_my_program_test COMMAND /path/to/generator --executable-path $<TARGET_FILE:my_target> -o /path/to/script/file
    DEPENDS /path/to/generator
    BYPRODUCTS /path/to/script/file
)
# (run the test script via cmake --build ... --target run_my_program_test)

# option 3
add_test(NAME my_program_test1 COMMAND my_program -parameter1 -parameter2)
...
enable_testing()
include(CTest)
# run the test from the build dir via ctest -R my_program_test1


Answered By - fabian
Answer Checked By - Timothy Miller (WPSolving Admin)