How to pass a list variable to another CMake call?

2019-08-31 12:21发布

问题:

In my CMake scripts, I run other CMake instances using exec_program(${CMAKE_COMMAND} ...). I want to make the ${CMAKE_MODULES_PATH} of the parent environment available to the child environments. Therefore, I tried to pass the variable as argument:

exec_program(${CMAKE_COMMAND} ... ARGS ...
    -DCMAKE_MODULE_PATH=${CMAKE_MODULE_PATH} ...)

This messes up the other parameters and I get a CMake Error: The source directory <first-module-path> does not appear to contain CMakeLists.txt.. Therefore, I tried escaping the variable:

exec_program(${CMAKE_COMMAND} ... ARGS ...
    -DCMAKE_MODULE_PATH="${CMAKE_MODULE_PATH}" ...)

When I print the ${CMAKE_MODULE_PATH} form within the child environment, all the paths get printed, separated by a space each. However, CMake doesn't find scripts inside those paths. I guess it has something to do with the list being passed as string rather than a semi-color separated list.

How can I pass a CMake variable holding a list of strings to another CMake command?

回答1:

In my CMake scripts, I run other CMake instances using exec_program(${CMAKE_COMMAND} ...)

According to documentation this command is deprecated:

Deprecated. Use the execute_process() command instead.

Example with the list variable, CMakeLists.txt:

execute_process(
    COMMAND "${CMAKE_COMMAND}" "-DVAR=A;B;C" -P script.cmake
    OUTPUT_VARIABLE output
)

script.cmake:

message("VAR: ${VAR}")

foreach(x ${VAR})
  message("x: ${x}")
endforeach()

output:

VAR: A;B;C
x: A
x: B
x: C


标签: cmake