How to copy DLL files into the same folder as the executable using CMake?


I put these lines in my top-level CMakeLists.txt file. All the libraries and executables will be placed in the top level of the build directory so that the executables can find the libraries and it is easy to run everything.


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.

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?

Copying files and including them in a CPack archive

As explained in the documentation of the CPack module, the binary installers created by CPack contain everything installed via CMake's INSTALL command. Thus the executable mytarget in your example will be included in the CPack archive, because you use the install command to copy it to the bin folder.

To also have CPack include the example folder in the generated archive, you can use the DIRECTORY variant of the install command in the following way:

install(DIRECTORY "${PROJECT_SOURCE_DIR}/examplefiles/" DESTINATION "example")

The file(COPY ...) and configure_file(...) do not have an effect on what is installed by CPack. Both command are usually used to copy files from the source tree to the binary tree upon configuring the CMake project.

Using add_custom_command with ${CMAKE_COMMAND} -E copy_directory ... will postpone the actual copying of files to the build time of the project. It will however not trigger the inclusion of the copied files in the CPack archive, either.

Copy .dll file to the same folder as that of .exe file using CMake

As Tsyvarev already commented - the destination expression is invalid. In addition, your source line is incomplete (until you want to copy the whole folder which needs another command)

The right command would be

add_custom_command(TARGET abc POST_BUILD 
               COMMAND ${CMAKE_COMMAND} -E copy_if_different

in case you're building also the dll via cmake and you know the target name you could write

add_custom_command(TARGET abc POST_BUILD 
               COMMAND ${CMAKE_COMMAND} -E copy_if_different

where xyz is the target name of the dll

you might also have a look on this one: How to copy DLL files into the same folder as the executable using CMake?