nowox
nowox

Reputation: 29116

How to properly add two numbers in a Makefile

I would like to know which solution is better to add two numbers in a Makefile. In my case I will would use the function add as shown below:

result = $(call add, 34, 56)
$(error $(result))                        

Solution 1:

add    = $(shell echo $$(( $(1) + $(2) )))

Solution 2:

add    = $(shell perl -e 'print $1 + $2')

Solution 3:

add    = $(shell echo '$1 + $2' | bc | tr '\n' ' ')

Solution 4:

16 := x x x x x x x x x x x x x x x
_input_int := $(foreach a,$(16),$(foreach b,$(16),$(foreach c,$(16),$(16)))))

_decode = $(words $1)
_encode = $(wordlist 1,$1,$(_input_int))
_plus = $1 $2
_max = $(subst xx,x,$(join $1,$2))

_push = $(eval stack := $$1 $(stack))
_pop = $(word 1,$(stack))$(eval stack := $(wordlist 2,$(words $(stack)),$(stack)))
_pope = $(call _encode,$(call _pop))
_pushd = $(call _push,$(call _decode,$1))

calculate=$(eval stack:=)$(foreach t,$1,$(call handle,$t))$(stack)
handle   =$(call _pushd,                                          \
            $(if $(filter +,$1),                                  \
              $(call _plus,$(call _pope),$(call _pope)),          \
                $(call _encode,$1)))

add     = $(strip $(foreach v,$(2), $(call calculate, $v $(1) +))) 

I admit the solution 4 is ridiculous but it is the only one that does not depend on an external tool such as bash, perl or bc.

Upvotes: 5

Views: 2043

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136425

Try GNU Make Standard Library, it provides integer arithmetic functions.

Upvotes: 3

Related Questions