Volker Stolz
Volker Stolz

Reputation: 7402

Using bash arithmetic expansion in GNU makefile

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.

Upvotes: 1

Views: 314

Answers (2)

bobbogo
bobbogo

Reputation: 15493

$ 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 :-).)

Upvotes: 1

ensc
ensc

Reputation: 6994

add

SHELL = bash

to the makefile

Upvotes: 4

Related Questions