cmakeparallel-builds

Run-time dependency on generated file in CMake


I have a test (add_executable(MyTest ...)) which needs a file at run-time. The file is generated using a custom command. I would like to model that run-time dependency in CMake.

Currently, there is a build-time dependency on the generated file using add_dependencies(MyTest GenerateFile) where GenerateFile is a custom target that depends on the custom command's output. Disadvantage: MyTest does not start compiling code until GenerateFile has finished building. This is unnecessary -- I would like to build MyTest and generate the file in parallel.

Another option I considered was to add a new target MyTestAndGenerateFile that depends on both MyTest and GenerateFile. Disadvantage: Calling make MyTest does not generate the file any more. One has to remember to call make MyTestAndGenerateFile instead.

Alternatively, the new target could be called MyTest and the test could be added using add_executable(MyTest_Code ...). Disadvantage: When using the Visual Studio generator, the test code will now be located in a project called MyTest_Code instead of MyTest, which breaks naming conventions. Also, you now have to build the MyTest project, but run the MyTest_Code project, so you cannot use Set as start-up project any more.

In short, I am looking for a form of add_dependencies saying that the dependency is not needed at build time, but rather at run time.


Solution

  • What you can try is to add a test that invokes the target GenerateFile, and make your actual test depend on the former. Something like this:

    add_test(NAME MakeGenerateFile COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target GenerateFile)
    add_test(MyTest MyTest)
    set_tests_properties(MyTest PROPERTIES DEPENDS MakeGenerateFile)