3

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?

kayahr
  • 20,913
  • 29
  • 99
  • 147

3 Answers3

1

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/

Jean-Francois T.
  • 11,549
  • 7
  • 68
  • 107
1

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)))
Lai Jiangshan
  • 1,420
  • 1
  • 13
  • 23
0

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)'
Community
  • 1
  • 1
Harvey
  • 5,703
  • 1
  • 32
  • 41