CMake compile time generation of source

c++, cmake

Solution

Yes, it is possible. You do that by providing a custom command to generate the files, so that CMake learns how to generate them. Here's an example:

add_executable(generator gen1.cpp gen2.cpp)

add_custom_command(
  OUTPUT generated_file1.cpp generated_file2.cpp
  COMMAND generator -options --go here
  COMMENT "Running generator"
  VERBATIM
)

add_executable(something_else
  fixed1.cpp
  fixed2.cpp
  generated_file1.cpp
  generated_file2.cpp
)

This way, CMake will know the files are generated, and will introduce proper dependencies as well - typing `make something_else` in a clean build dir will build `generator`, then run it, then build `something_else`.

Problem

I have the following situation with CMake: it has to build two applications: a. generator b. something_else The generator is nothing fancy, a few CPP files linked together The something_else is: a. a few "normal" CPP files b. generated CPP/h files which I have to link in. These CPP files are generated by the generator The generator is configured in the configure phase with some choices, depending on these options the content of the generated files is different. And here I get an error: If I specify all the files (generated and not) in the `add_application` of something_else the configure phase chokes on it since it cannot find the generated files... obviously because they were not generated yet, since the generator was not built and executed yet. So the question: Is this possible using CMake? If yes, how?

Original source