CMake compile time generation of source

2019-04-11 12:05发布

问题:

I have the following situation with CMake:

  1. it has to build two applications:

    a. generator

    b. something_else

  2. The generator is nothing fancy, a few CPP files linked together

  3. 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?

回答1:

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.



回答2:

You need to tell CMake that the files are generated:

set_source_files_properties(someautogeneratedfile.cpp PROPERTIES GENERATED TRUE)
set_source_files_properties(someothergeneratedfile.h PROPERTIES GENERATED TRUE)

Now you just need to make sure that you run your generator before you run your something_else step. There are ways to manage that too, check out

add_custom_command(...)
add_custom_target(...)
add_dependencies(...)


标签: c++ cmake