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

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

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

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

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

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

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

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

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

all:
  @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.

About Pratik Sinha

Linux Nerd, Socialist, Atheist, Adventuristic, Nature Lover, Geeky.

Leave a Reply