You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CMake 3.x中如何将字符串作为execute_process的输入流?

How to Pass a String as Input to execute_process in CMake 3.x

Great question! CMake's execute_process doesn’t include a direct INPUT_STRING parameter like it does INPUT_FILE, but there are reliable workarounds depending on your use case—let’s break them down:

CMake has a built-in cross-platform echo command via cmake -E echo, which avoids shell-specific syntax headaches across Windows, Linux, and macOS. You can pipe its output directly to your target command:

# Define your input string
set(MY_INPUT_STRING "Hello from CMake! This works across all platforms.")

execute_process(
    # Output the string using CMake's cross-platform echo
    COMMAND ${CMAKE_COMMAND} -E echo "${MY_INPUT_STRING}"
    # Pipe the output to your actual tool (replace `cat` with your command)
    COMMAND cat
    # Capture and clean up the result if needed
    OUTPUT_VARIABLE COMMAND_OUTPUT
    OUTPUT_STRIP_TRAILING_WHITESPACE
)

# Verify the result
message(STATUS "Command output: ${COMMAND_OUTPUT}")

This approach is clean, no temporary files required, and avoids shell compatibility issues. Just note: if your string has special characters (like nested quotes), you may need to escape them properly in the CMake variable.

Option 2: Temporary File (Best for Complex/Specialized Strings)

If your input has lots of special characters (newlines, backslashes, quotes) and you want to avoid pipeline edge cases, writing to a temporary file and using INPUT_FILE is the most reliable method:

set(MY_COMPLEX_INPUT "Line 1\nLine 2 with \"quoted text\"\nLine 3 with backslashes: \\")

# Write the string to a temp file in your build directory
file(WRITE "${CMAKE_BINARY_DIR}/temp_input.txt" "${MY_COMPLEX_INPUT}")

execute_process(
    COMMAND cat  # Replace with your target command
    INPUT_FILE "${CMAKE_BINARY_DIR}/temp_input.txt"
    OUTPUT_VARIABLE COMMAND_OUTPUT
)

# Clean up the temp file (optional but good practice)
file(REMOVE "${CMAKE_BINARY_DIR}/temp_input.txt")

message(STATUS "Complex input output: ${COMMAND_OUTPUT}")

This method eliminates all shell escaping issues and works for even the most complicated input strings.

You could use shell-native echo commands, but this introduces platform dependencies that can break builds across systems. For example:

Unix-like systems:

execute_process(
    COMMAND bash -c "echo 'Hello Unix' | cat"
    OUTPUT_VARIABLE UNIX_OUTPUT
)

Windows:

execute_process(
    COMMAND cmd /c "echo Hello Windows | findstr /v \"\""
    OUTPUT_VARIABLE WINDOWS_OUTPUT
)

Unless you’re targeting a single platform, skip this approach—it’s prone to syntax and behavior mismatches between shells.

内容的提问来源于stack exchange,提问作者einpoklum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:14:21