cmake fails at generating step with add_custom_command() when not located in same directory than add_executable()
Here is a simple testcase where I'm failing to achieve my goal: generate a source file from a add_custom_command() in a subdirectory of the main project executable.
All tests have been tested with cmake 3.13.4 (from Debian 10) and cmake 3.16.4 (binary package from kitware) with identical results.
The attached archive contains my testcase. each directory contains a run.log of commands I have run.
1) good:
add_custom_command()
and target_sources()
are in the same CMakeList.txt
than the add_executable()
. Everything is working fine.
CMakeLists.txt
:
cmake_minimum_required(VERSION 3.13)
project(Test)
add_executable(test)
add_custom_command(
OUTPUT generated.c
COMMAND echo "int gen_value = ${GEN_VALUE}\;" > ${CMAKE_CURRENT_BINARY_DIR}/generated.c
COMMENT "building generated.c"
)
target_sources(test PUBLIC main.c ${CMAKE_CURRENT_BINARY_DIR}/generated.c)
2) bad:
add_custom_command()
and target_sources()
are in a src directory while add_executable()
stays in the top CMakeLists.txt
.
CMakeLists.txt
:
cmake_minimum_required(VERSION 3.13)
project(Test)
add_executable(test)
add_subdirectory(src)
src/CMakeLists.txt
:
add_custom_command(
OUTPUT generated.c
COMMAND echo "int gen_value = ${GEN_VALUE}\;" > ${CMAKE_CURRENT_BINARY_DIR}/generated.c
COMMENT "building generated.c"
)
target_sources(test PUBLIC main.c ${CMAKE_CURRENT_BINARY_DIR}/generated.c)
On the 1st cmake run, it fails upon generation step:
-- Configuring done
CMake Error at CMakeLists.txt:4 (add_executable):
Cannot find source file:
/home/gilles/tmp/cmake/bad/build/src/generated.c
Tried extensions .c .C .c++ .cc .cpp .cxx .cu .m .M .mm .h .hh .h++ .hm
.hpp .hxx .in .txx
CMake Error at CMakeLists.txt:4 (add_executable):
No SOURCES given to target: test
3) bad2:
I have added a add_custom_target()
and a add_dependencies()
to add an explicit dependencies list from test to generated.c
src/CMakeLists.txt
:
add_custom_command(
OUTPUT generated.c
COMMAND echo "int gen_value = ${GEN_VALUE}\;" > ${CMAKE_CURRENT_BINARY_DIR}/generated.c
COMMENT "building generated.c"
)
add_custom_target(gen_target
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/generated.c
)
add_dependencies(test gen_target)
target_sources(test PUBLIC main.c ${CMAKE_CURRENT_BINARY_DIR}/generated.c)
On the 1st run, cmake fails as above.
If I create by hand a generated.c
file with a touch build/src/generated.c
, the build succeeds until it tries to compile generated.c
(which is normal as it's an empty file). However on the subsequents runs, it works well to identify the configuration change, the need to rebuild generated.c and to build a working executable.
What am I missing or what am I doing wrong ? Is it a cmake bug or is it that I'm having wrong expectations ?
Thanks, Gilles.