Reputation: 22050
I need to do some simple math in a Makefile but can't find out how to do it. In a shell script I would do it like this:
A=1
B=2
C=$[$A+$B]
But how can I do this in a Makefile? Let's use this as a base:
A=1
B=2
C=$(A)+$(B)
all:
@echo 'A is $(A)'
@echo 'B is $(B)'
@echo 'C is $(C)'
Naturally this outputs C is 1+2
. How can I rewrite the definition of the variable C
so the Makefile outputs C is 3
?
Upvotes: 3
Views: 9033
Reputation: 12940
I have found the two following methods, both using shell, that work pretty well: $$(( ... )) and expr ...
A=1
B=2
#With Double-dollar
SUM_1 = $(shell echo $$(( $(A) + $(B) )))
#With 'expr'
SUM_2 = $(shell expr $(A) + $(B) )
$(info Sum with Double-$$: $(SUM_1))
$(info Sum with 'expr': $(SUM_2))
Note that when using expr
, you shall put spaces around the +
or it will return 1+2
. This is not required when using $$
.
.
When you have bc
available, you should go with it as it is much clearer code:
A=1
B=2
SUM = $(shell echo $(A)+$(B) | bc )
$(info Sum with 'bc': $(SUM))
I found the following page very interesting: http://www.humbug.in/2010/makefile-tricks-arithmetic-addition-subtraction-multiplication-division-modulo-comparison/
Upvotes: 1
Reputation: 5821
Like Lai said...
A=1
B=2
C=$(shell echo $$(( $(A) + $(B) )) )
all:
@echo 'A is $(A)'
@echo 'B is $(B)'
@echo 'C is $(C)'
Upvotes: 0
Reputation: 1420
use "$(())" in shell
all:
@echo C is $$(($(C)))
Edit after one years later:
I did not know you need to used the final value of $C in the Makefile. (You just shown it is only used in the shell script inside the Makefile or I had make mistake) You just need to move my code to the definition of the $C:
C=$(shell echo $$(($A+$B)))
Upvotes: 1