如何使用 CMake 将 DLL 文件复制到与可执行文件相同的文件夹中? [英] How to copy DLL files into the same folder as the executable using CMake?

查看:118
本文介绍了如何使用 CMake 将 DLL 文件复制到与可执行文件相同的文件夹中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用 CMake 在我们的 SVN 中生成源代码的 Visual Studio 文件.现在我的工具需要一些 DLL 文件与可执行文件位于同一文件夹中.DLL 文件位于源旁边的文件夹中.

We use CMake for generating the Visual Studio files of our sources in our SVN. Now my tool requires some DLL files to be in the same folder as the executable. The DLL files are in a folder alongside the source.

如何更改我的 CMakeLists.txt 以便生成的 Visual Studio 项目要么已经在发布/调试文件夹中具有特定的 DLL 文件,要么在编译时复制它们?

How can I change my CMakeLists.txt such that the generated Visual Studio project will either have already the particular DLL files in the release/debug folders or will copy them upon compilation?

推荐答案

我会使用 add_custom_commandcmake -E copy_if_different... 来实现这一点.如需完整信息,请运行

I'd use add_custom_command to achieve this along with cmake -E copy_if_different.... For full info run

cmake --help-command add_custom_command
cmake -E


所以在你的情况下,如果你有以下目录结构:

So in your case, if you have the following directory structure:

/CMakeLists.txt
/src
/libs/test.dll

并且该命令适用的 CMake 目标是 MyTest,然后您可以将以下内容添加到 CMakeLists.txt:

and your CMake target to which the command applies is MyTest, then you could add the following to your CMakeLists.txt:

add_custom_command(TARGET MyTest POST_BUILD        # Adds a post-build event to MyTest
    COMMAND ${CMAKE_COMMAND} -E copy_if_different  # which executes "cmake - E copy_if_different..."
        "${PROJECT_SOURCE_DIR}/libs/test.dll"      # <--this is in-file
        $<TARGET_FILE_DIR:MyTest>)                 # <--this is out-file path


如果你只想复制/libs/目录的全部内容,使用cmake -E copy_directory:

If you just want the entire contents of the /libs/ directory copied, use cmake -E copy_directory:

add_custom_command(TARGET MyTest POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy_directory
        "${PROJECT_SOURCE_DIR}/libs"
        $<TARGET_FILE_DIR:MyTest>)


如果您需要根据配置(例如发布、调试)复制不同的 dll,那么您可以将它们放在以相应配置命名的子目录中:/libs/Release/libs/调试.然后,您需要在 add_custom_command 调用中将配置类型注入到 dll 的路径中,如下所示:

If you need to copy different dlls depending upon the configuration (Release, Debug, eg) then you could have these in subdirectories named with the corresponding configuration: /libs/Release, and /libs/Debug. You then need to inject the configuration type into the path to the dll in the add_custom_command call, like this:

add_custom_command(TARGET MyTest POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy_directory
        "${PROJECT_SOURCE_DIR}/libs/$<CONFIGURATION>"
        $<TARGET_FILE_DIR:MyTest>)

这篇关于如何使用 CMake 将 DLL 文件复制到与可执行文件相同的文件夹中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆