How to prepend all filenames on the list with common path?

后端 未结 6 1804
孤城傲影
孤城傲影 2020-12-16 09:05

How can I prepend all filenames on the list with a common path prefix automatically? For instance having a list of files in CMakeLists.txt:

SET(SRC_FILES foo         


        
相关标签:
6条回答
  • 2020-12-16 09:31

    As an improvement to Ding-Yi Chen's answer, if you still need to support pre-3.12 CMake as I do, you can use following code:

    function(list_transform_prepend var prefix)
        set(temp "")
        foreach(f ${${var}})
            list(APPEND temp "${prefix}${f}")
        endforeach()
        set(${var} "${temp}" PARENT_SCOPE)
    endfunction()
    

    Advantage of this solution is, that interface is closer to one is CMake 3.12 list(TRANSFORM ...) and the change is done in-place.

    Used like this

    list_transform_prepend(FILES_TO_TRANSLATE "${CMAKE_CURRENT_SOURCE_DIR}/")
    
    0 讨论(0)
  • 2020-12-16 09:32

    Following function may be what you want.

    FUNCTION(PREPEND var prefix)
       SET(listVar "")
       FOREACH(f ${ARGN})
          LIST(APPEND listVar "${prefix}/${f}")
       ENDFOREACH(f)
       SET(${var} "${listVar}" PARENT_SCOPE)
    ENDFUNCTION(PREPEND)
    

    To use it,

    PREPEND(FILES_TO_TRANSLATE ${CMAKE_CURRENT_SOURCE_DIR} ${SRC_FILES})
    
    0 讨论(0)
  • 2020-12-16 09:36

    CMake 3.12 added list transformers - one of these transformers is PREPEND. Thus, the following can be used inline to prepend all entries in a list:

    list(TRANSFORM FILES_TO_TRANSLATE PREPEND ${CMAKE_CURRENT_SOURCE_DIR})

    ...where FILES_TO_TRANSLATE is the variable name of the list.

    More information can be found in the CMake documentation.

    0 讨论(0)
  • 2020-12-16 09:36
    string(REGEX REPLACE "([^;]+)" "ANYPREFIX/\\1.cpp" outputlist "${inputlist}")
    

    Replace ANYPREFIX with any prefix and '.cpp' with any suffix you need.

    0 讨论(0)
  • 2020-12-16 09:47

    You need to use a foreach loop. But if you use that in several parts of your project, you might want to create a function or a macro.

    0 讨论(0)
  • 2020-12-16 09:53

    I assume that you want an absolute filename as you are prepending ${CMAKE_CURRENT_SOURCE_DIR}. If you are using FILE(GLOB <VAR> <PATTER>), all the files will have an absolute path already:

    file(GLOB_RECURSE SOURCE_FILES src/*.cpp)
    

    See the comments CMake in documentation on why not to use GLOB to add source files.

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