Feature Request: Genex: Add $<FILTER:list,regex>
CMake does not provide a generator expression to filter lists. This prevents a clean implementation of the following use-case.
Consider an executable main
which depends on a generated source file baz.c
that is generated from a list of .cfg
files. Each .cfg
file logically belongs to a separate CMake target. In the example below, these are the libraries foo
and bar
. The generator shall process a .cfg
file only if main
is linked against its corresponding CMake target.
CMake makes it possible to obtain the list of source files using $<TARGET_PROPERTY:main,SOURCES>
. However, this list contains much more files than just .cfg
files. In particular, the generated file baz.c
itself is part of that list which will result in a cyclic dependency. Moreover, the add_custom_command
responsible for the generator execution requires a list of all .cfg
files for its DEPENDS
argument. This is necessary to ensure that the generator is only executed when necessary.
add_executable(main)
target_sources(main PRIVATE
main.c
"${CMAKE_CURRENT_BINARY_DIR}/baz.c"
)
add_custom_command(
OUTPUT baz.c
# Problem: CMake provides no means to obtain all .cfg files from
# the SOURCES target property of 'main' at generation time. Just
# using $<TARGET_PROPERTY:main,SOURCES> creates a cyclic dependency
# and moreover makes the generation of 'baz.c' dependent on unrelated
# files.
DEPENDS $<TARGET_PROPERTY:main,SOURCES>
# Solution: $<FILTER:$<TARGET_PROPERTY:main,SOURCES>,*.cfg> to obtain
# the list of all .cfg files contained in SOURCES.
COMMAND ${CMAKE_COMMAND}
ARGS -E echo "Generate baz.c from $<TARGET_PROPERTY:main,SOURCES>."
COMMAND ${CMAKE_COMMAND}
ARGS -E touch baz.c # baz.c depends on *.cfg
)
target_link_libraries(main PRIVATE foo bar)
add_library(foo)
target_sources(foo
PRIVATE foo.c
INTERFACE foo.cfg
)
add_library(bar)
target_sources(bar
PRIVATE bar.c
INTERFACE bar.cfg
)
Note: An alternative solution would be to maintain a separate target property for the list of .cfg
files. This would require custom INTERFACE
properties that behave like file lists. See also #18217.