skip to Main Content

I would like to use bash‘s arithmetic expansion for binary operations in a Makefile (GNU make + bash on Debian). These are not covered by expr. I need this in a Makefile:

$ x=$(( 255 & 2#11110000)); echo $x
240

Things that don’t work:

$ cat Makefile 
all: a b

a: # $ interpreted by make
    x=$(( 255 & 2#11110000)); echo $$x

b: # escaped $
    x=$$(( 255 & 2#11110000)); echo $$x

(a) obviously doesn’t work, and (b) doesn’t either:

$ make b
x=$(( 255 & 2#11110000)); echo $x
/bin/sh: 1: arithmetic expression: expecting EOF: " 255 & 2#11110000"

What’s a possible way? Generous amounts of quoting, backticking and escaping also yielded no results.

2

Answers


  1. add

    SHELL = bash
    

    to the makefile

    Login or Signup to reply.
  2. $ cat Makefile
    
    # Make variable (recommended)
    x := $(shell bash -c 'echo $$((255 & 2#11110000))')
    $(info [$x])
    
    # Shell variable (not recommended)
    a:
        x=`bash -c 'echo $$((255 & 2#11110000))'`; echo $$x
    

    Giving

    $ make
    [240]
    x=`bash -c 'echo $((255 & 2#11110000))'`; echo $x
    240
    

    Don’t forget that # introduces a comment in a makefile!

    I recommend using make facilities rather than shell facilities wherever possible. It usually turns out to be cleaner. (As @ensc says, I do — I use bash everywhere in my makefiles :-).)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search