add_custom_command GENERATED sources added to a target in a different directory via target_sources() are not generated
Consider this project
# CMakeLists.txt
cmake_minimum_required(VERSION 3.18)
project(proj LANGUAGES CXX)
add_subdirectory(sub1)
set(foo "${CMAKE_CURRENT_BINARY_DIR}/foo.cpp")
set(foo "${CMAKE_CURRENT_SOURCE_DIR}/foo.cpp")
add_custom_command(
OUTPUT "${foo}"
COMMAND "${CMAKE_COMMAND}" -E touch "${foo}"
VERBATIM
COMMENT "Generating: ${foo}"
)
#set_source_files_properties("${foo}" TARGET_DIRECTORY "app" PROPERTIES GENERATED TRUE) # line x
#add_custom_target(generating_target DEPENDS "${foo}" COMMENT "Running target generating_target") # line y
target_sources(app PRIVATE "${foo}")
# sub1/CMakeLists.txt
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/main.cpp" "int main(int argc, char**argv) {return 0;}")
add_executable(app "${CMAKE_CURRENT_BINARY_DIR}/main.cpp")
As is it is, configuring errors out:
$ cmake ..
-- Configuring done
CMake Error at sub1/CMakeLists.txt:2 (add_executable):
Cannot find source file:
/Volumes/T3/Dev/projects/cmake/general/defer_target_sources/foo.cpp
Tried extensions .c .C .c++ .cc .cpp .cxx .cu .m .M .mm .h .hh .h++ .hm
.hpp .hxx .in .txx .f .F .for .f77 .f90 .f95 .f03 .ispc
If I uncomment line x
, configuring succeeds, but building fails.
$ ninja
[2/4] Building CXX object sub1/CMakeFiles/app.dir/__/foo.cpp.o
FAILED: sub1/CMakeFiles/app.dir/__/foo.cpp.o
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk -MD -MT sub1/CMakeFiles/app.dir/__/foo.cpp.o -MF sub1/CMakeFiles/app.dir/__/foo.cpp.o.d -o sub1/CMakeFiles/app.dir/__/foo.cpp.o -c ../foo.cpp
clang: error: no such file or directory: '../foo.cpp'
clang: error: no input files
Excerpt from build.ninja
:
#############################################
# Assume dependencies for generated source file.
build ../foo.cpp: CUSTOM_COMMAND || cmake_object_order_depends_target_app
restat = 1
If I also uncomment line y
, the file is successfully generated and the build succeeds.
I guess marking a file as GENERATED
is not enough to convince CMake that the file should be generated by the custom command?
Is the proper fix to fix CMake to handle something like this? Is there some other workaround that can be applied that does not require creation of a custom target to force generation of the file?
Edited by alcroito