Wednesday, October 26, 2022

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

Issue

I am working on CMake for generating the visual studio files. I would like to add the xyz.dll in the same folder where abc.exe is residing.

I had read somewhere that when i manually copy the xyz.dll file into the same folder where abc.exe is residing then the problem would be solved. But every time it is not possible.. I want to write the CMake command so that it will find the xyz.dll file and copy into the same folder where the abc.exe is residing..

Following mentioned are the paths where the .exe and .dll file is residing in my PC.

  ${MyWorkSpace_ROOT_DIR}/algoCommon/pthread/dll/xyz.dll
  ${MyWorkSpace_ROOT_DIR}/xml/addAlgo/.../cmakeOut.VS12/Debug/abc.exe

abc is my Project and i would like to confirm whether the following mentioned is wrong or not.

add_custom_command(TARGET abc PRE_BUILD 
                   COMMAND ${CMAKE_COMMAND} -E copy_if_different
                   "${MyWorkSpace_ROOT_DIR}/algoCommon/pthread/dll"              
$<{MyWorkSpace_ROOT_DIR}/xml/addAlgo/.../cmakeOut.VS12/Debug/:abc>)

If this is wrong kindly correct me. If it is correct then I would like to ask few doubts.. will this command automatically copies the xyz.dll files into the folder abc.exe is residing or something else is happening here??


Solution

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
               "${MyWorkSpace_ROOT_DIR}/algoCommon/pthread/dll/xyz.dll"              
                $<TARGET_FILE_DIR:abc>)

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
               $<TARGET_FILE:xyz>              
               $<TARGET_FILE_DIR:abc>)

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?



Answered By - jenseb
Answer Checked By - Mary Flores (WPSolving Volunteer)