CMake: how to use if condition in add_custom_command(...)
Asked Answered
A

2

6

I want to use Linux if condition in CMakeLists.txt by add_custom_command(...) for i need run these if condition and do some judgement in makefile. Like this:

cmake_minimum_required(VERSION 2.8)
add_custom_target(temp_target ALL)
add_custom_command(TARGET temp_target
                   PRE_BUILD
                   COMMAND if ["a" != "b"]; then echo 1; fi;
                   VERBATIM )

What should i do if i want to use

if ["a" != "b"]; then echo 1; fi;

when make a makefile? Thanks a lot for you help!

Arman answered 19/4, 2016 at 7:27 Comment(1)
if it doesnt work like that, why dont you try to add these in a function and then call the function in the command?Stratus
I
5

You may specify one-line shell code with using /bin/sh -c as COMMAND argument:

COMMAND /bin/sh -c "if [ 'a' != 'b' ]; then echo 1; fi;"

Note, that [ is an extension of the bash, it may be unknown for simple shells like "dash".

Intermixture answered 19/4, 2016 at 7:58 Comment(4)
Thanks for you reply, but what you give seem does not work in my computer.Arman
DONOT forget to add VERBATIM within add_custom_command !!Frontwards
as @Master Yoda says, preceed semicolons with backslashRoundlet
@jackytse: Inside a string, escaping of semicolons is no longer needed.Intermixture
A
1

You may need to preceed semicolons with backslash

COMMAND if [ 'a' != 'b' ] \; then echo 1\; fi\;
Alliterative answered 3/6, 2019 at 14:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.