How do I perform arithmetic in a makefile?
Using Bash arithmetic expansion:
SHELL=/bin/bash
JPI=4
JPJ=2
all:
echo $$(( $(JPI) * $(JPJ) ))
The first line is to choose the Bash shell instead of the default (sh). Typically, sh doesn't support arithmetic expansion. However in Ubuntu, /bin/sh is provided by Dash, which supports this feature. So that line could be skipped.
The double dollar sign is because we want the expansion to be done by the shell. Note: the JPI and JPJ variables are expanded by make first, then the expression is passed to bash like this:
$(( 4 * 2 ))
Answer from @mrkj is great but as @Daniel mentions, not all systems have bc
(for example, I don't have it on MSys).
I have found the two following methods, both using shell: $$(( ... )) and expr ...
JPI=4
JPJ=2
#With Double-dollar
JPIJ_1 = $(shell echo $$(( $(JPI) + $(JPJ) )))
#With 'expr'
JPIJ_2 = $(shell expr $(JPI) + $(JPJ) )
$(info Sum with Double-$$: $(JPIJ_1))
$(info Sum with 'expr': $(JPIJ_2))
Note that when using expr
, you shall put spaces around the +
or it will return 4+2
. This is not required when using $$
.
.
When you have bc
available, you might definitely go with it. I found the following page very interesting: http://www.humbug.in/2010/makefile-tricks-arithmetic-addition-subtraction-multiplication-division-modulo-comparison/
If you're using GNU make
and have bc
installed on your system, you can use something like this:
JPI=4
JPJ=2
FOO=$(shell echo $(JPI)\*$(JPJ) | bc)
all:
echo $(FOO)
It's clumsy (or brilliant, depending on your perspective), but you can do arithmetic directly in GNU make. See Learning GNU Make Functions with Arithmetic. Be aware though that this method doesn't scale well. It will work wonderfully for small numbers as you have shown in your question, but it doesn't do well when you're working with numbers with a large magnitude (greater than 10,000,000).
In GNU Make with Guile support (i.e. since version 4.0) it is easy to use call to Scheme language for arithmetic or other calculations. It is done without creating any subshell or child process.
An example
JP-I := 4
JP-J := 2
JP-IJ := $(guile (* $(JP-I) $(JP-J) ))
$(info JP-IJ = $(JP-IJ) )
# prints: JP-IJ = 8
See also the manual for Guile Arithmetic Functions.
A possible check for Guile:
ifeq (,$(filter guile,$(.FEATURES)))
$(error Your Make version $(MAKE_VERSION) is not built with support for Guile)
endif