Copy target file to another location in a post build step in CMake

前端 未结 3 868
攒了一身酷
攒了一身酷 2020-12-04 17:11

I have a dynamic library that gets a different name depending on configuration, specified in the CMake scripts by:

set_target_properties(${name} PROPERTIES O         


        
相关标签:
3条回答
  • 2020-12-04 17:21

    Use generator expressions in the POST_BUILD command instead of manually computing the output path. These are configuration aware. Example:

    add_custom_command(TARGET mylibrary POST_BUILD 
      COMMAND "${CMAKE_COMMAND}" -E copy 
         "$<TARGET_FILE:mylibrary>"
         "my_target_path/$<CONFIGURATION>/$<TARGET_FILE_NAME:mylibrary>" 
      COMMENT "Copying to output directory")
    
    0 讨论(0)
  • 2020-12-04 17:31

    Rather than using the obsolete LOCATION property, prefer using generator expressions:

    add_custom_command(TARGET mylibrary POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:mylibrary> ${targetfile}
    )
    

    You could also just generate the exe in the target directory directly by setting the target property RUNTIME_OUTPUT_DIRECTORY instead of copying it. This has per-configuration options (e.g. RUNTIME_OUTPUT_DIRECTORY_DEBUG).

    set_target_properties(mylibrary PROPERTIES
                          RUNTIME_OUTPUT_DIRECTORY_DEBUG <debug path>
                          RUNTIME_OUTPUT_DIRECTORY_RELEASE <release path>
    )
    

    For further details run:

    cmake --help-property "RUNTIME_OUTPUT_DIRECTORY"
    cmake --help-property "RUNTIME_OUTPUT_DIRECTORY_<CONFIG>"
    

    Also, you should be able to use forward slashes throughout for path separators, even on Windows.

    0 讨论(0)
  • 2020-12-04 17:31

    The other answers weren't 100% clear to me...

    Say you're building an executable test_base.exe, the following will build the executable then copy the .exe to the base 'build' directory:

    add_executable(test_base "")
    target_sources(test_base
        PRIVATE
            catch_main.cpp
            catch_tests.cpp
            sc_main.cpp
    )
    target_link_libraries(test_base PRIVATE Catch2 systemc)
    
    add_custom_command(TARGET test_base POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:test_base> ${PROJECT_BINARY_DIR}/test_base.exe
        COMMENT "Created ${PROJECT_BINARY_DIR}/test_base.exe"
    )
    

    So, after this runs your project will have:

    <project dir>/build/test_base.exe

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