CMake: adding custom resources to build directory

前端 未结 2 665
情话喂你
情话喂你 2021-02-18 21:53

I am making a small program which requires an image file foo.bmp to run
so i can compile the program but to run it, i have to copy foo.bmp to \'build\' subdirectory manually

2条回答
  •  感情败类
    2021-02-18 22:42

    To do that you should use add_custom_command to generate build rules for file you needs in the build directory. Then add dependencies from your targets to those files: CMake only build something if it's needed by a target.

    You should also make sure to only copy files if you're not building from the source directory.

    Something like this:

    project(foo)
    
    cmake_minimum_required(VERSION 2.8)
    
    # we don't want to copy if we're building in the source dir
    if (NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR)
    
        # list of files for which we add a copy rule
        set(data_SHADOW yourimg.png)
    
        foreach(item IN LISTS data_SHADOW)
            message(STATUS ${item})
            add_custom_command(
                OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${item}"
                COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/${item}" "${CMAKE_CURRENT_BINARY_DIR}/${item}"
                DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/${item}"
            )
        endforeach()
    endif()
    
    # files are only copied if a target depends on them
    add_custom_target(data-target ALL DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/yourimg.png")
    

    In this case I'm using a "ALL" custom target with a dependency on the yourimg.png file to force the copy, but you can also add dependency from one of your existing targets.

提交回复
热议问题