Search code examples
cmake

How to have Makefile generated by CMake check if an environment variable is set


I'm using CMake to generate Makefiles under Linux.

I'd like the Makefile to check if an environment variable is set (sort of How to ensure Makefile variable is set as a prerequisite?): I'd like make to generate an error if a mandatory env var is not set (else it fails to compile and it's hard for the developper to understand why). Obviously, I cannot modify the Makefile by hand to do that, but I'd like this code to be added to the Makefile by CMake.

Is that doable?


Solution

  • Same logic except using a CMake script. So the solution is cross-platform.

    Created check_env.cmake:

    if(NOT DEFINED ENV{VAR_REQUIRED})
            message(FATAL_ERROR "VAR_REQUIRED not found!")
    endif()
    

    Create a custom target so the check is done at build time:

    add_custom_target(check_env ALL
        COMMAND ${CMAKE_COMMAND} -P check_env.cmake
    )