CMake 为什么不能将 .exe 用于自定义目标

CMake Why cannot use .exe for custom target

这里是CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
project("cmake_oneoneone")
add_executable(main src/main.cpp)
set(library_name liba CACHE string "This variable is the library name")
add_library(${library_name} STATIC src/liba.cpp)
target_link_libraries(main ${library_name})
include_directories(include)
add_custom_target(run_main
              COMMAND ./main
              DEPENDS main
              )

输出为:

~/workspace/cmake_test/build$ make run_main
[ 50%] Built target liba
[100%] Built target main 
Hello world!
[100%] Built target run_main

但是如果我将可执行文件更改为 .exe

cmake_minimum_required(VERSION 2.8)
project("cmake_oneoneone")
add_executable(main.exe src/main.cpp)
set(library_name liba CACHE string "This variable is the library name")
add_library(${library_name} STATIC src/liba.cpp)
target_link_libraries(main.exe ${library_name})
include_directories(include)
add_custom_target(run_main
              COMMAND ./main.exe
              DEPENDS main.exe
              )

~/workspace/cmake_training/build$ make run_main
make[3]: *** No rule to make target `../main.exe', needed by `CMakeFiles/run_main'.  Stop.
make[2]: *** [CMakeFiles/run_main.dir/all] Error 2
make[1]: *** [CMakeFiles/run_main.dir/rule] Error 2
make: *** [run_main] Error 2

我在 CMake 上尝试了 Linux 和 Windows,两者的行为相同。

如果您查看 ADD_EXECUTABLE 命令的文档,您会发现 CMake 会自动将扩展名 .exe 添加到您的可执行文件中,以防您在 Windows 环境中生成它。如果你在Linux,显然生成一个.exe是没有意义的:

Adds an executable target called to be built from the source files listed in the command invocation. The corresponds to the logical target name and must be globally unique within a project. The actual file name of the executable built is constructed based on conventions of the native platform (such as .exe or just ).

因此您不必在可执行文件名称的末尾添加 .exe。