Search code examples
shellcmakecmake-languagecmakelists-options

How to call a cmake method from shell script?


I have a parameterised function in mytestprogram.cmake written like below:

function(get_output_from_input output input) 
    set(${output} "test" PARENT_SCOPE)
endfunction()

Question:
How do I call the cmake method get_output_from_input from a shell script?

I learnt that there is -P <source.cmake> flag, that puts CMake into script processing mode and we can execute arbitrary CMake code with it using something like below.

execute_process(COMMAND ${CMAKE_PROGRAM} -P yourscript.cmake)

So, in this case I believe the way to call get_output_from_input from a shell script would be something like below?

input="some_input"
output=""
execute_process(get_output_from_input(output, input) ${CMAKE_PROGRAM} -P mytestprogram.cmake)
echo $output

But above trick does not work. Is the way I am running execute_process correct?

Trying to figure out whats wrong, it seems echo $CMAKE_PROGRAM returns empty? Could that be the reason? What am I missing here to call get_output_from_input?

Environment:
cmake version 3.18.2
macOS Catalina


Solution

  • cmake -P executes an entire script, not a single function defined in a CMake file, so need to add an additional script file that you can then execute via cmake -P. Arguments to a script executed via cmake -P need to be passed as CMake variables, e.g. cmake -DINPUT=some_input -P myscript.cmake .

    Since you need the output of the CMake script in an bash variable, the CMake script "mytestscript.cmake" would look something like this:

    # make `get_output_from_input` available in current script
    # assuming the script file is located next to `mytestprogram.cmake`
    include(${CMAKE_CURRENT_LIST_DIR}/mytestprogram.cmake)
    
    get_output_from_input(RESULT "${INPUT}")
    
    message("${RESULT}")
    

    and the shell script contains

    #!/bin/bash
    input="some_input"
    
    # assumes `mytestscript.cmake` is located in the current working directory
    output=$(cmake -DINPUT="${input}" -P mytestscript.cmake 2>&1)
    
    # Below statement should print the value of output.
    echo $output
    

    Regarding execute_process: That is meant to be used if you need to execute another process from within a CMake script, not to execute a CMake script from a shell process. Depending on what you plan to do with the output of the CMake script you could possibly use execute_process instead of additional bash.