How to do arithmetic operation in makefile?

2019-09-02 11:04发布

问题:

I am performing the following in the makefile to measure the time taken in doing some operation:-

START=$(shell date +%s) <br>
@if [ -s mfill.mapi.diff ]; then echo "difference exist between GOLDEN map file and test map file, see mfill.map.diff" ; fi <br>
END=$(shell date +%s) <br>
DIFF_SUB=$(shell echo $(END)\-$(START) | bc) <br>
@echo "It took ${DIFF_SUB} seconds"

It results in following output :-

START=1309941257
END=1309941268
DIFF_SUB=
It took seconds

Could you guys suggest where i did wrong?

回答1:

I don't think you should be using curly braces for Makefile variables: $(END) not ${END}

You want subtraction but you used a '*'.

jcomeau@intrepid:/tmp$ cat Makefile 
START=3
END=5
DIFF_SUB=$(shell echo $(END)-$(START) | bc)
test:
    @echo it took $(DIFF_SUB) seconds
jcomeau@intrepid:/tmp$ make
it took 2 seconds

If you're doing these inside the target, use your curly braces but double $s: $${DIFF_SUB}

jcomeau@intrepid:/tmp$ cat Makefile 
START=3
END=5
DIFF_SUB=$(shell echo $(END)-$(START) | bc)
test:
    @echo it took $(DIFF_SUB) seconds
test2:
    @START=3 && \
    echo HELLO && \
    END=7 && \
    DIFF_SUB=$$(($$END - $$START)) && \
    echo it took $${DIFF_SUB} seconds
jcomeau@intrepid:/tmp$ make test test2
it took 2 seconds
HELLO
it took 4 seconds