1

I've read:

cmake custom command to copy and rename

and I want to do something similar, but rather than copying a file, I want to generate a file. If that wasn't in a custom command, I would write:

file(WRITE "generated.c" "int main() { return 0; }")

but it doesn't seem like cmake -E supports this directly. What should I do (other than run something platform-dependent)?

einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

1

Use CMake's script mode (-P). In CMakeLists.txt:

cmake_minimum_required(VERSION 3.21)
project(test)

file(
  GENERATE
  OUTPUT "gen.cmake"
  CONTENT [[
cmake_minimum_required(VERSION 3.21)
file(WRITE "${OUT}" "int main() { return 0; }")
]])

add_custom_command(
  OUTPUT generated.c
  COMMAND ${CMAKE_COMMAND} -DOUT=generated.c 
          -P gen.cmake
  DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/gen.cmake"
)

add_executable(main "${CMAKE_CURRENT_BINARY_DIR}/generated.c")

Note that if the file you generate has configuration-dependent contents, then you must include $<CONFIG> somewhere in the file name. See the docs here for more detail: https://cmake.org/cmake/help/latest/command/file.html#generate

Alex Reinking
  • 16,724
  • 5
  • 52
  • 86