user3518295
user3518295

Reputation: 328

Passing environment variable to the COMMAND in CMake execute_process

I have the following CMake snippet that runs COMMAND in WORKING_DIRECTORY. I tried different ways to pass the environment variable (MBEDTLS_INCLUDE_DIR=${CMAKE_CURRENT_SOURCE_DIR}/../mbedtls/mbedtls/include) but without success.

The snippet that works (without env variable):

set(BUILD_CMD cargo build --features parsec-client/no-fs-permission-check)
set(WORKING_DIR "${CMAKE_CURRENT_SOURCE_DIR}/parsec_se_driver")

execute_process( COMMAND ${BUILD_CMD}
                 RESULT_VARIABLE CMD_ERROR
                 WORKING_DIRECTORY ${WORKING_DIR} )

if(NOT ${CMD_ERROR} MATCHES "0")
MESSAGE(SEND_ERROR "BUILD_CMD STATUS:" ${CMD_ERROR})
endif()

How can I pass the env variable to the execute_process?

If I write something like this:

execute_process( COMMAND MBEDTLS_INCLUDE_DIR=${CMAKE_CURRENT_SOURCE_DIR}/../mbedtls/mbedtls/include cargo build --features parsec-client/no-fs-permission-check
                 RESULT_VARIABLE CMD_ERROR
                 WORKING_DIRECTORY ${WORKING_DIR} )

or taking different parts to variables, or adding quotes, I get:

BUILD_CMD STATUS:No such file or directory

Upvotes: 5

Views: 6854

Answers (2)

Connor Fuhrman
Connor Fuhrman

Reputation: 831

This should work also:

execute_process(
   COMMAND /bin/bash -c "CC=/usr/bin/gcc make"
)

Upvotes: 0

Kevin
Kevin

Reputation: 18243

As recommended in the CMake mailing list here, your solution using set(ENV ...) is perfectly valid:

set(ENV{MBEDTLS_INCLUDE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/../mbedtls/mbedtls/include)
execute_process( 
    COMMAND ${BUILD_CMD}
    RESULT_VARIABLE CMD_ERROR
    WORKING_DIRECTORY ${WORKING_DIR}
)

You could also use CMake's command line utility to run the command in a modified environment using cmake -E env:

execute_process( 
    COMMAND ${CMAKE_COMMAND} -E env 
        MBEDTLS_INCLUDE_DIR="${CMAKE_CURRENT_SOURCE_DIR}/../mbedtls/mbedtls/include" ${BUILD_CMD}
    RESULT_VARIABLE CMD_ERROR 
    WORKING_DIRECTORY ${WORKING_DIR}
)

Upvotes: 12

Related Questions