CMake 3.x中如何将字符串作为execute_process的输入流?
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:
Option 1: Cross-Platform Echo + Pipeline (Recommended for Most Cases)
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.
Option 3: Shell-Specific Pipelines (Not Recommended for Cross-Platform Projects)
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

