[CMake] How to set environment variable for custom command

Dan Kegel dank at kegel.com
Fri Jul 19 11:39:44 EDT 2013


On Fri, Jul 19, 2013 at 8:21 AM, Andreas Pakulat <apaku at gmx.de> wrote:
>> In Unix shell we can do that:
>> $ VAR=foo cmd in out
>> I would like to be able to do the same for a custom command in CMake.

See http://public.kitware.com/Bug/view.php?id=5145
for previous discussion.

>> add_custom_command(
>>   OUTPUT out
>>   COMMAND cmd in out
>>   DEPENDS in
>>   ENVIRONMENT VAR foo
>>   )
>
> I can see two options to achieve this: ...
> b) let cmake generate a shell script (using configure_file) and set the
> envvar in there, it would also contain the command executable and pass on
> any arguments using $@. Then use the script as custom command instead of the
> real command.

c) On Mac and Linux, you can do it inline something like this:

 add_custom_command(
   OUTPUT out
   COMMAND "FOO=${bar}" my_cmd.sh"
   DEPENDS in
   )

On Windows, you might be able to do it inline like this:

 add_custom_command(
   OUTPUT out
   COMMAND "set FOO=${bar}" & my_cmd.bat"
   DEPENDS in
   )

(although I haven't tried it, so in both cases you might need to
coax cmake into using a shell by prefixing the command with sh -c
or cmd /c or something.)


More information about the CMake mailing list