0

(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
user2771324
  • 307
  • 3
  • 13
  • 1
    Setting `CMAKE_C_COMPILER` after the `project()` call is a source of many subtle problems. See that [my answer](https://stackoverflow.com/a/63944545/3440745) for more details. Either set the compiler before the `project()` call, or, better, do not set it in `CMakeLists.txt` at all. – Tsyvarev Sep 08 '22 at 12:26
  • Why do you think you need to copy the exe after building it? Usually one of the following approaches is preferrable: 1. Set `CMAKE_RUNTIME_OUTPUT_DIRECTORY` in the toplevel `CMakeLists.txt` before any target creation or `add_subdirectory` command. (This is to put all dlls and executables in the same directory when building.) 2. Add `install(TARGETS)` possibly specifying the `DESTINATION` for the `RUNTIME` part. This would produce logic for copying the files during `cmake --install ...` and when building packages via `cpack`. – fabian Sep 08 '22 at 18:54
  • @fabian Because I need the exe at multiple places. – user2771324 Sep 10 '22 at 05:13

1 Answers1

0

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).

user2771324
  • 307
  • 3
  • 13