cmake: read and compile dynamically-generated list of cpp files

前端 未结 3 607
既然无缘
既然无缘 2021-01-18 15:17

I have a custom tool that processes a given list of IDL files and produces a number of .cpp and .h files as output. I want to add those files to the list of things to compil

相关标签:
3条回答
  • 2021-01-18 15:28

    There is a function that build the list directly from file:

    file(STRINGS <filename> <variable> [<options>...])
    

    source: https://cmake.org/cmake/help/v3.11/command/file.html

    0 讨论(0)
  • 2021-01-18 15:31

    This is a few years late but this works just fine:

    #run whatever tool that generates the cpp files
    execute_process(COMMAND "./your_tool.sh")
    
    #read files from files.txt and make a cmake 'list' out of them
    file(READ "files.txt" SOURCES)
    
    #found this technique to build the cmake list here:
    #http://public.kitware.com/pipermail/cmake/2007-May/014236.html
    #maybe there is a better way...
    STRING(REGEX REPLACE ";" "\\\\;" SOURCES "${SOURCES}")
    STRING(REGEX REPLACE "\n" ";" SOURCES "${SOURCES}")
    
    #at this point you have your source files inside ${SOURCES}
    #build a static library...?
    add_library(mylib STATIC ${SOURCES})
    
    0 讨论(0)
  • 2021-01-18 15:49

    CMake needs to be able to infer the names of all .cpp files participating in the build at configure time. It is not possible to add files afterwards without re-running CMake.

    One possible approach would be to use a two-phase CMake build: Instead of building the generated source files directly from your main project, you create a separate CMake project for building just the generated sources.

    Then in your main CMake project you add a custom target that runs after the code generation and invokes CMake to both configure and build the generated files project.

    The disadvantage here is that the generated files no longer appear as part of the main project. Also some trickery is required if you don't want to rebuild the generated sources every time - custom targets are always considered out-of-date, so you might want to use a script here that only runs CMake on the subproject if the generated files changed.

    0 讨论(0)
提交回复
热议问题