Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

c++ - Cmake generator expressions

I'm trying for long time to understand the benefit of generator expressions such as $<xxx:yy> in CMake, when and how to use them. Can anybody explain it clearly with some examples. Many thank in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

CMake does first parse the CMakeLists.txt files in your project - named "Configuration Phase" - and then it generates your build environment - named "Generation Phase".

So basically the generator expressions are for everything only the generator could know:

  • The name and path of target outputs (mainly when cross-compiling and in multi-configuration environments)
  • Or more generally any target property that the generator evaluates to mingle together the compiler/linker calls

Here are examples where I use generator expressions in my project:

  1. Copying files next to the executable (in multi-configuration environments you can't just use variables like CMAKE_CURRENT_BINARY_DIR)

    add_custom_command(
        TARGET library1 
        POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy
            "$<TARGET_FILE:library1>"
            "$<TARGET_FILE_DIR:mainProject>/$<TARGET_FILE_NAME:library1>"
    )
    

    CMake post-build-event: copy compiled libraries

    add_custom_command(
        TARGET myBinary 
        POST_BUILD
            COMMAND ${CMAKE_COMMAND} -E copy  
                         "${CMAKE_CURRENT_SOURCE_DIR}/myTest.txt" 
                         "$<TARGET_FILE_DIR:myBinary>/myTest.txt"
    )
    

    how do I add external test files to a cmake project

  2. Differentiate e.g. DEBUG or RELEASE configurations

    add_compile_options("$<$<CONFIG:DEBUG>:/MDd>")
    

    For Cmake, can you modify the release/debug compiler flags with `add_compiler_flags()` command?

    Modern way to set compiler flags in cross-platform cmake project

  3. With the TARGET_PROPERTY generator expression you could do a lot of things e.g.

    file(GENERATE 
        OUTPUT "includes.txt" 
        CONTENT "$<TARGET_PROPERTY:motor,INCLUDE_DIRECTORIES>
    "
    )
    

    CMake doesn't pick up INTERFACE_INCLUDE_DIRECTORIES of linked library


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...