[CMake] if (DEFINED $ENV{VAR}) doesn't work as expected

Michael Wild themiwi at gmail.com
Tue Oct 11 14:55:02 EDT 2011


On 10/11/2011 06:02 PM, Glenn Coombs wrote:
> Hi,
> 
> I've just had a CMakeLists.txt fail to work as expected because somebody
> was testing to see whether an environment variable was set with the
> syntax: if (DEFINED $ENV{VAR}).  This short example shows the problem:
> 
> cmake_minimum_required(VERSION 2.8)
> 
> project(foo)
> 
> message("HOME: $ENV{HOME}")
> if (DEFINED $ENV{HOME})
>     message("HOME is defined")
> else()
>     message("HOME is NOT defined")
> endif()
> 
> if (DEFINED FOO)
>     message("At 1: FOO is defined")
> else()
>     message("At 1: FOO is NOT defined")
> endif()
> 
> set(FOO "foo")
> 
> if (DEFINED FOO)
>     message("At 2:FOO is defined")
> else()
>     message("At 2:FOO is NOT defined")
> endif()
> 
> When run it prints this:
> 
> HOME: /user/grc
> HOME is NOT defined
> At 1: FOO is NOT defined
> At 2:FOO is defined
> 
> So the test for if a variable is defined works for cmake variables but
> not for environment variables.  I can work around this by testing if the
> environment variable is the empty string I guess.  Is the current
> behaviour what is wanted, or is this a bug ?
> 
> --
> Glenn

That's because it should read

if(DEFINED ENV{VAR})

notice the missing $. Otherwise you are testing whether a variable is
defined whose name is given by the content of the VAR environment variable.

HTH

Michael



More information about the CMake mailing list