bug: target_sources generator expression when target in other directory
target_sources since CMake 3.13 works with targets in other directories. target_sources() is noted to work with generator expressions.
However, it appears there is a long-standing bug--since relative directories were allowed in CMake 3.13--with generator expressions. I tested a few CMake versions including 3.14, 3.22 and all behave incorrectly. I tried with Ninja and Make.
Use case: we have target with sources scattered throughout directories, and looking to eliminate error-prone, cumbersome script if()
with gen expr in target_sources() in each source directory
MWE:
top-level CMakeLists.txt
cmake_minimum_required(VERSION 3.13...3.22)
project(gen LANGUAGES C)
add_executable(hello)
add_subdirectory(src)
src/CMakeLists.txt
target_sources(hello PRIVATE $<1:main.c>)
Where $<1:
stands in for actual logic, for simplicity. Removing the generator expression it works but the point is to use generator expressions with CMake >= 3.13 relative directories in target_sources()
CMake Error at CMakeLists.txt:5 (add_executable):
Cannot find source file:
main.c
Yes, one could workaround with OBJECT library in each source directory, but that adds more chances for mistakes/typos. And it looks from docs like target_sources supposed to work with generator expressions in relative directories.