SIGSTACKFAULT
SIGSTACKFAULT

Reputation: 1035

Makefile - Get arguments passed to make

I have a makefile like so:

.SILENT: #don't echo commands as we run them.

###
# here, set $1 (in the latter bash script) to the first make arg.
# $2 to the second one.
# et cetera.
# ($0 being set properly is optional)
###

foo:
    echo "you passed to make: $1 $2 $3 $4 $5 $6"

so i can do:

make foo
You passed to make: foo

(don't tell anyone, but i'm creating a 'make me a sandwich' thing)

Upvotes: 17

Views: 33161

Answers (2)

SIGSTACKFAULT
SIGSTACKFAULT

Reputation: 1035

Edit 2019: Wow, past-me was so stupid.


Alright, I figured out my own question.

You can create a shell script to have total control:

$ cat make.sh
if [ $1 = 'me' ]; then
    if [ $1 = 'a' ]; then
        if[ $3 = 'sandwich' ];then
            if [ `whoami` = 'root' ];
                echo "Okay."
                #todo: echo an actual sandwich in ascii.
            else
                echo "what? Make it yourself!"
            fi
            exit 0
        fi
    fi
fi

make $@

$ echo 'alias make="/home/connor/make.sh"' >> .bashrc
$ source .bashrc

...tada! now when you call make, it'll actually call the shell script, check if the arguments you passed to make are 'make me a sandwich', and if they aren't, call make with all of it's args.

if you want to tell make to run a rule for certain args:

if [ $1 = 'foo' ]; then
    make somerule
fi

Upvotes: 5

Alex Cohn
Alex Cohn

Reputation: 57183

No, you cannot "see" the full list of arguments of the make command in a Makefile. You can see the list of "targets" in the order they were entered on the command line, e.g.

make a   c b   d

will produce $(MAKECMDGOALS) with a c b d.

You can specifically check that something was set on the make command line, e.g.

make A=B C=D

will produce $(A) with B, and $(C) with D. But you will never know if it was make A=B C=D or make C=D A=B or make A=F -B C=D A=B.

If it is really important, you can wrap your make in a shell script, and have the full power of it:

make.sh a A=B c

calls

#!/bin/bash
make MAKECMDLINE="$*" $*

Now inside the Makefile, you can parse $(MAKECMDLINE) as you wish.

Note that some command-line options may disable your parser, e.g.

make A=B C=D -h

will never read your Makefile, and

make A=B C=D -f /dev/null

will also ignore your Makefile.

Upvotes: 12

Related Questions