Prophet60091
Prophet60091

Reputation: 609

Pass bash shell variable to Makefile?

Inside my env.sh:

export BIN="/home/user/stuff"

Inside my Makefile:

blah blah

TARGET = filetobeinstalled

blah blah

install:
       cp $(TARGET) $(BIN)

Prior to running make install, I define my env vars within my bash shell like this: source /home/user/env.sh. I double check that these env vars are working by typing echo $BIN in the shell that I'm running the Makefile, which gives me the appropriate response (/home/user/stuff).

So, I'm trying to pass the $BIN variable defined at the shell prompt with source, to inside of my Makefile, which references $BIN, but does not define it. Unfortunately, when I run make install, it does not pick up $BIN as you can see from the output

$ source /home/user/env.sh
$ echo $BIN
$ /home/user/stuff
$ make install

make[1]: Entering directory `/home/user/stufftoinstall'
cp filetobeinstalled
cp: missing destination file operand after `filetobeinstalled'
Try `cp --help' for more information.
make[1]: *** [install] Error 1

On the line that has cp filetobeinstalled, I would expect it to pick up my env vars set using source prior to running make install so that line should read cp filetobeinstalled /home/user/stuff instead, but it doesn't.

I've found similar posts and bits and pieces scattered around the interwebs, but nothing definitive for the above problem and/or nothing that has worked so far. Hopefully this isn't too obvious, but go easy on me as I'm definitely a Makefile-nubile.

Cheers

Upvotes: 3

Views: 3923

Answers (1)

bobah
bobah

Reputation: 18864

Make sure to export variables you define in the env file, only environment variables are passed to a child process, not shell local ones. And I would make the name longer (like in the below example) to avoid possible clashes with anything else.

export BINDIR=/bin/path ;# will do
BINDIR=/bin/path; export BINDIR ;# will do as well
BINDIR=/bin/path make install ;# even this willd
make BINDIR=/bin/path install ;# and this, though using a different mechanism

Addition:

If you add the below target then you can run make var=whatever printvar and it will print the value of the variable whatever. It may help debugging it.

.PHONY: printvar
printvar:
    @echo "[$(var)]=[$($(var))]"

In addition, if you run make with -np it will run in a dry run mode and will print all defined variables, so you can do make -np install | fgrep -w BIN and see what you have.

Upvotes: 1

Related Questions