Search code examples
cmakebuild

cmake: copy .exe target output to destination fails (file extension problem?)


(cmake version 3.24.1; on Linux with mingw32)
For example, such configuration will fail with "Error copying file /build/path/to/my_program".
How to fix it without changing target name?

add_executable(my_program main.c)
set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc)
add_custom_command(TARGET my_program POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:my_program> /path/to/
)

The problem seems to be that cmake cannot match target "my_program" to actual file "my_program.exe".

According to what I tried, dll target works out of box, but exe target needs workaround to append .exe to target name. Is there anyway to avoid changing target name?

target-type    target-name    real-output    cmake-target-name    can-copy
executable     basename       basename.exe   basename             No
module         basename       basename.dll   basename.so          Yes
executable     basename.exe   basename.exe   basename.exe         Yes

Solution

  • Thanks @Tsyvarev for answer in comments above.

    Use a cmake toolchain and remove CMAKE_C_COMPILER fixes the problem.

    -1 Sample toolchain for mingw32:
    https://gist.github.com/peterspackman/8cf73f7f12ba270aa8192d6911972fe8
    -2 Change CMakeLists.txt:

    +++ set(CMAKE_TOOLCHAIN_FILE mingw-w64-x86_64.cmake)
    --- set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc)
    

    -3 Clean build directory (or maybe delete CMakeCache.txt).