add_custom_command output referenced in an interface library does not work
I am trying to use a add_custom_command
to generate an output file at build time, i.e. a header file, which is actually referenced in a target created using add_library(... INTERFACE)
in the same directory.
The relevant part of the documentation states that this should be possible, i.e.
This defines a command to generate specified OUTPUT file(s). A target created in the same directory (CMakeLists.txt file) that specifies any output of the custom command as a source file is given a rule to generate the file using the command at build time.
However, the following prototype causes CMake to fail with an error stating that the header file is missing. CMake nevertheless completes writing the build files, but the generator is not executed during build. In contrast, when I set
USE_STATIC_LIB
to true
everything works as expected. However, this is not a clean solution since an actual dummy library must be created.
### CMakeLists.txt
cmake_minimum_required(VERSION 3.9)
project(my_project C)
set(USE_STATIC_LIB false)
add_subdirectory(src)
add_executable(my_executable
main.c # Empty main returning zero.
)
target_link_libraries(my_executable
my_library
)
### src/CMakeLists.txt
add_custom_command(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/my_generated_header.h
COMMAND "echo" "EXECUTING GENERATOR..."
)
if (USE_STATIC_LIB)
add_library(my_library STATIC)
target_sources(my_library PRIVATE
dummy.c # Empty c-file.
${CMAKE_CURRENT_BINARY_DIR}/my_generated_header.h
)
else()
add_library(my_library INTERFACE)
target_sources(my_library INTERFACE
${CMAKE_CURRENT_BINARY_DIR}/my_generated_header.h
)
endif()