0

我在使用 CMake list(APPEND ...)时遇到了一个非常奇怪的问题。我的脚本如下(只是一个例子):

cmake_minimum_required(VERSION 3.20)
include(CMakePrintHelpers)

project(exe)
file(WRITE ${PROJECT_NAME}.cpp "#include <iostream>
#include \"test1.h\"
#include \"test2.h\"
void main() {
    std::cout << \"Hello world!\" << std::endl;
}")
add_executable(${PROJECT_NAME} "exe.cpp")

set(COMMANDS "echo /* empty file */ > test1.h"
             "echo /* empty file */ > test2.h")

foreach(CMD IN LISTS COMMANDS)
    list(APPEND CMDS COMMAND "cmd.exe /c \"${CMD}\"")
endforeach()

cmake_print_variables(PROJECT_NAME CMDS)
add_custom_target(${PROJECT_NAME}_headers1
                    ${CMDS}
                    BYPRODUCTS test1.h test2.h
                    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
                    VERBATIM)
add_dependencies(${PROJECT_NAME} ${PROJECT_NAME}_headers1)

set(CMDS COMMAND cmd.exe /c "echo /* empty file */ > test1.h"
         COMMAND cmd.exe /c "echo /* empty file */ > test2.h")
cmake_print_variables(PROJECT_NAME CMDS)
add_custom_target(${PROJECT_NAME}_headers2
                    ${CMDS}
                    BYPRODUCTS test1.h test2.h
                    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
                    VERBATIM)
add_dependencies(${PROJECT_NAME} ${PROJECT_NAME}_headers2)

生成产生以下输出:

d:\play\cmake>cmake.exe -G"Ninja" -S. -B"build/ninja"
-- PROJECT_NAME="exe" ; CMDS="COMMAND;cmd.exe /c "echo /* empty file */ > test1.h";COMMAND;cmd.exe /c "echo /* empty file */ > test2.h""
-- PROJECT_NAME="exe" ; CMDS="COMMAND;cmd.exe;/c;echo /* empty file */ > test1.h;COMMAND;cmd.exe;/c;echo /* empty file */ > test2.h"
-- Configuring done
-- Generating done
-- Build files have been written to: D:/play/cmake/build/ninja

我预计两个自定义目标都将运行相同的命令。但是, build.ninja 文件以不同的方式处理每个自定义目标:

#############################################
# Custom command for CMakeFiles\exe_headers1

build CMakeFiles\exe_headers1 test1.h test2.h: CUSTOM_COMMAND
  COMMAND = cmd.exe /C "cd /D D:\play\cmake && PRE_BUILD && "cmd.exe \c \"echo \* empty file *\ > test1.h\"" && "cmd.exe \c \"echo \* empty file *\ > test2.h\"""
  restat = 1


#############################################
# Custom command for CMakeFiles\exe_headers2

build CMakeFiles\exe_headers2 test1.h test2.h: CUSTOM_COMMAND
  COMMAND = cmd.exe /C "cd /D D:\play\cmake && PRE_BUILD && cmd.exe /c "echo /* empty file */ > test1.h" && cmd.exe /c "echo /* empty file */ > test2.h""
  restat = 1

有谁知道如何防止 list(APPEND ...) 从“翻转”斜杠(“/”)到反斜杠(“\”)?更奇怪的是 cmake_print_variables(...) 输出不受影响。

提前致谢。-乌里

4

0 回答 0