Makefile Tricks: Arithmetic – Addition, Subtraction, Multiplication, Division, Modulo, Comparison

While working on a project, I needed to do some calculations inside a Makefile. Took me sometime to figure out how, hence jotting it down. Here’s a sample makefile where I have show examples of standard calculations.

NUMBER1 := 10
NUMBER2 := 5

ADD := $(shell echo ${NUMBER1}+${NUMBER2} | bc)

SUBTRACT := $(shell echo ${NUMBER1}-${NUMBER2} | bc)

MULTIPLY := $(shell echo ${NUMBER1}*${NUMBER2} | bc)

DIVIDE := $(shell echo ${NUMBER1}/${NUMBER2} | bc)

#Division (Floating Point)
DIVIDEF := $(shell echo "scale=3; ${NUMBER2}/${NUMBER1}" | bc)

MODULO := $(shell echo ${NUMBER1}%${NUMBER2} | bc)

#Comparison Greater Than
COMPARISON1 := $(shell echo ${NUMBER1}\>=${NUMBER2} | bc)

#Comparison Smaller Than
COMPARISON2 := $(shell echo ${NUMBER2}\<=${NUMBER2} | bc)

  @echo Addition ${ADD}
  @echo Subtraction ${SUBTRACT}
  @echo Multiplication ${MULTIPLY}
  @echo Division ${DIVIDE}
  @echo Division  - Floating Point ${DIVIDEF}
  @echo Modulo ${MODULO}
  @echo Comparison Greater Than ${COMPARISON1}
  @echo Comparison Smaller Than ${COMPARISON2}

Besides what is shown above, you can use anything that bc supports like boolean operators, relational expressions etc.

To execute the above code, copy the code to a file and name the file Makefile. Run the make command in the directory you created the Makefile in. You should see the following output.

@$ make
Addition 15
Subtraction 5
Multiplication 50
Division 2
Division - Floating Point .500
Modulo 0
Comparison Greater Than 1
Comparison Smaller Than 1

Hope this helps.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.