作为示例,假设四个文件夹(app1,app2,app3和main)如下所示
main
|__ CMakeLists.txt
\__ module1
|______ CMakeLists.txt
|______ sub1.cpp
|______ sub1.h
\__ library5
|______ CMakeLists.txt
|______ sub5.cpp
|______ sub5.h
\__app1
\__app2
\__app3
其中module1的输出是module1.dll,而library5的输出是lib5.dll。 app1的文件夹必须包含module1.dll和lib5.dll,app2需要lib5.dll,最后app3需要module1.dll(应用程序,模块和lib的数量超过此示例,正如我在下面解释的那样,我们不想更改模块/库的
CMakeLists.txt
,而main / cc是我们的)。PS:
我有一个
CMakeLists.txt
项目,其中有几个库和模块。它们使用cmake
命令包含在我的项目中(请注意,我的项目仅由多个模块组成,并且没有任何add_subdirectory
或add_library
)。我需要复制库/模块的输出而不更改它们的
add_target
(带有CMakeLists.txt
选项的add_custom_command
实际上不是一个好选择,因为在这一点上,我需要更改库/模块的输出,而不仅仅是它们。属于我的项目)。另一方面,它必须在具有其他(库/模块)的外部(主要)POST_BUILD
中完成。我尝试了其他命令,例如
CMakeLists.txt
和CMakeLists.txt
,但是我认为它们在生成file (COPY )
阶段时可以运行,并且只能复制预构建阶段中存在的资源文件。此外,在另一种方法中,我编写了一个bash脚本文件来复制文件,并通过bellow命令在主
configure_file()
中调用它。add_custom_target (copy_all
COMMAND ${CMAKE_SOURCE_DIR}/copy.sh ${files}
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)
cmake-cache
具有文件列表。但是复制没有执行!我手动测试了可以正常工作的脚本。但是我不知道为什么它不能在CMakeLists.txt中调用时运行。我该怎么做才能将子项目的输出从主要的
CMakeLists.txt
复制到某些位置? 最佳答案
设置
为了简化一点,假设您有:
CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(PostBuildCopyFromRoot)
add_subdirectory(module)
module / CMakeLists.txt
file(WRITE "module.h" "int ModuleFunc();")
file(WRITE "module.cpp" "int ModuleFunc() { return 1; }")
add_library(module SHARED "module.cpp" "module.h")
target_include_directories(module PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}")
set_target_properties(module PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS 1)
app / app.mexw64
问题
如果现在仅将以下内容添加到根
CMakeLists.txt
:add_custom_command(
TARGET module
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
"$<TARGET_FILE:module>"
"app/$<TARGET_FILE_NAME:module>"
)
您将从CMake获得:
CMake Warning (dev) at CMakeLists.txt:8 (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.
TARGET 'module' was not created in this directory.
解决方案
您始终可以覆盖命令行为:
function(add_library _target)
_add_library(${_target} ${ARGN})
add_custom_command(
TARGET ${_target}
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
"$<TARGET_FILE:${_target}>"
"${CMAKE_SOURCE_DIR}/app/$<TARGET_FILE_NAME:${_target}>"
)
endfunction()
注意:将代码段放在
add_subdirectory()
调用之前参考文献
Copying executable and DLLs to User specified location using CMake in windows
Parent CMakeLists.txt overwriting child CMakeLists.txt output directory options
Proper usage of CMAKE_*_OUTPUT_DIRECTORY
Is there a way to include and link external libraries throughout my project only editing my top level CMakeList?
关于c++ - 如何使用主要CMakeLists.txt中的cmake复制目标文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45832911/