Dyno Fu
Dyno Fu

Reputation: 9044

Greater than string comparison in a Makefile

How do I express the following logic in a Makefile?

if $(XORG_VERSION) > "7.7"
   <do some thing>
fi

Conditional Parts of Makefiles only provides ifeq or ifneq.

Upvotes: 15

Views: 9752

Answers (3)

levelont
levelont

Reputation: 626

Using shell commands, as mentioned in the other answers, should suffice for most use cases:

if [ 1 -gt 0 ]; then \
    #do something \
fi

However, if you, like me, want to use greater-than comparison in order to then set a make variable via make's $(eval) command, then you will find that attempting to do so using the other answer's model:

if [ 1 -gt 0 ]; then \
    $(eval FOO := value) \
fi

raises an error:

if [ 1 -gt 0 ]; then  fi;
/bin/bash: -c: line 0: syntax error near unexpected token `fi'
/bin/bash: -c: line 0: `if [ 1 -gt 0 ]; then  fi;'
make: *** [clean] Error 2```

I found a way how to sort out that problem and posted it as a solution to this other question. I hope someone finds it helpful!

Upvotes: 1

anatolyg
anatolyg

Reputation: 28251

I use the sort function to compare values lexicographically. The idea is, sort the list of two values, $(XORG_VERSION) and 7.7, then take the first value - if it's 7.7 then the version is the same or greater.

ifeq "7.7" "$(word 1, $(sort 7.7 $(XORG_VERSION)))"
   <do some thing>
endif

Adjust 7.7 to 7.8 if you need the strict greater-than condition.

This approach improves portability by avoiding shell scripts and concomitant assumptions about the capabilities of the available OS shell. However, it fails if the lexicographic ordering is not equivalent to the numerical ordering, for example when comparing 7.7 and 7.11.

Upvotes: 21

paxdiablo
paxdiablo

Reputation: 881403

You're not restricted to using the make conditional statements - each command is a shell command which may be as complex as you need (including a shell conditional statement):

Consider the following makefile:

dummy:
    if [ ${xyz} -gt 8 ] ; then \
        echo urk!! ${xyz} ;\
    fi

When you use xyz=7 make --silent, there is no output. When you use xyz=9 make --silent, it outputs urk!! 9 as expected.

Upvotes: 7

Related Questions