Makefile - Get arguments passed to make

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.


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

Tags:

Makefile