windows - CMake 找不到自定义命令 "ls"

标签 windows cmake

我尝试为我的 CLion 项目运行一些基本命令,但它就是行不通。这是我的 CMake 设置。

cmake_minimum_required(VERSION 3.6)
project(hello)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES main.cpp)
add_executable(hello ${SOURCE_FILES})

add_custom_command(OUTPUT hello.out
        COMMAND ls -l hello
        DEPENDS hello)

add_custom_target(run_hello_out
        DEPENDS hello.out)

我在 CLion 中运行 run_hello_out 时收到以下错误消息。

[100%] Generating hello.out
process_begin: CreateProcess(NULL, ls -l hello, ...) failed.
make (e=2): The system cannot find the file specified.
mingw32-make.exe[3]: *** [hello.out] Error 2
mingw32-make.exe[2]: *** [CMakeFiles/run_hello_out.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles/run_hello_out.dir/rule] Error 2
mingw32-make.exe: *** [run_hello_out] Error 2
CMakeFiles\run_hello_out.dir\build.make:59: recipe for target 'hello.out' failed
CMakeFiles\Makefile2:66: recipe for target 'CMakeFiles/run_hello_out.dir/all' failed
CMakeFiles\Makefile2:73: recipe for target 'CMakeFiles/run_hello_out.dir/rule' failed
Makefile:117: recipe for target 'run_hello_out' failed

它应该运行“ls -l hello”并在构建窗口或运行窗口中查看结果。

最佳答案

问题

CMake 不保证其 COMMAND 调用的 shell 上下文,它不会自动搜索 COMMAND 本身给定的可执行文件。

它主要将给定的命令放入生成的构建环境中,并取决于它在那里的处理方式。

在您的情况下,我假设您/CLion 在 MS Windows cmd shell 中运行 cmakemingw32-make。在这种情况下,您将不得不使用 dir 而不是 ls 命令:

add_custom_target(
    run_hello_out
    COMMAND dir $<TARGET_FILE_NAME:hello>
    DEPENDS hello
)

可能的解决方案

我看到三种可能的解决方案。要么

  1. 提供一个 bash shell 上下文

    include(FindUnixCommands)
    
    if (BASH)
        add_custom_target(
            run_hello_out
            COMMAND ${BASH} -c "ls -l hello"
            DEPENDS hello
        )
    endif()
    
  2. 使用 CMake 的 shell 抽象 cmake -E (只有有限数量的命令,例如没有 ls 等价物)

    add_custom_target(
        run_hello_out
        COMMAND ${CMAKE_COMMAND} -E echo $<TARGET_FILE:hello>
        DEPENDS hello
    )
    
  3. 使用 find_program() 搜索可执行文件.

    find_program(LS ls)
    
    if (LS)
        add_custom_target(
            run_hello_out
            COMMAND ${LS} -l hello
            DEPENDS hello
    endif()
    

引用

关于windows - CMake 找不到自定义命令 "ls",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39046025/

相关文章:

linux - smbclient - 发送目录中的所有文件

windows - 无法拉取 nanoserver :1903 Docker image

windows - LWP/IO::Socket::SSL 失败并返回 SSL3_GET_SERVER_HELLO:错误的密码

cmake - 未为 capnp_generate_cpp() 生成 cpp 文件

CMake、静态库和链接时间优化

c++ - Wl,--stack,4194304 错误 Visual Studio/CMake

c++ - 架构 x86_64 的 undefined symbol : OS X, Boost Log,CMake

java - 使用 Java 的 SunMSCAPI/Windows-MY 访问智能卡证书以进行 TLS/SSL 连接并进行客户端身份验证

带有具有冗余依赖项的子模块的 CMake 项目

c++ - wParam 为 0 时,什么时候会调用 WM_ENDSESSION?