Cmake:基于变量内容的add_custom_command参数

我想要一个Cmake函数将一些二进制文件复制到一个特定的位置.我有以下功能定义:

function ( collect_binaries TARGET_NAME DEST_DIR )
   set ( targetsToCopy ${ARGN} )

   set ( copy_cmd "COMMAND ${CMAKE_COMMAND} -E make_directory ${DEST_DIR}\n" )

   foreach ( target ${targetsToCopy} )
      LIST( APPEND copy_cmd "COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:${target}> ${DEST_DIR}$<TARGET_FILE_NAME:${target}>\n")
   endforeach( target ${targetsToCopy} )

   #message( FATAL_ERROR ${copy_cmd} )
   add_custom_target( ${TARGET_NAME} )
   add_custom_command( TARGET ${TARGET_NAME} PRE_BUILD ${copy_cmd} )

endfunction( collect_binaries )

以下用法:

collect_binaries( bin_copy ${PROJECT_BINARY_DIR}/out/ target_1 target_2 target3 )

我在项目树中定义了target_1,target_2和target_3.考虑到这一点,我得到了以下Cmake配置输出:

CMake Warning (dev) at binary_copy.cmake:15 (add_custom_command):

Policy CMP0040 is not set: The target in the TARGET signature of add_custom_command() must exist. Run “cmake –help-policy CMP0040”
for policy details. Use the cmake_policy command to set the policy and suppress this warning.

在这种情况下,目标似乎未知……但它确实存在并且没有拼写错误.这是什么问题?

最佳答案 您正在将collect_binaries函数中的copy_cmd变量设置为CMake字符串.然而,add_custom_command需要一个CMake列表来正确地解析参数,即:

function ( collect_binaries TARGET_NAME DEST_DIR )
   set ( targetsToCopy ${ARGN} )

   set ( copy_cmd COMMAND ${CMAKE_COMMAND} -E make_directory ${DEST_DIR} )

   foreach ( target ${targetsToCopy} )
      LIST( APPEND copy_cmd COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:${target}> "${DEST_DIR}$<TARGET_FILE_NAME:${target}>")
   endforeach( target ${targetsToCopy} )

   #message( FATAL_ERROR ${copy_cmd} )
   add_custom_target( ${TARGET_NAME} )
   add_custom_command( TARGET ${TARGET_NAME} PRE_BUILD ${copy_cmd} )

endfunction( collect_binaries )
点赞