How to pass argument to Makefile from command line?

Meng Lu picture Meng Lu · Jun 8, 2011 · Viewed 149.7k times · Source

How to pass argument to Makefile from command line?

I understand I can do

$ make action VAR="value"
$ value

with Makefile

VAR = "default"
action:
    @echo $(VAR)

How do I get the following behavior?

$ make action value
value

?

How about

$make action value1 value2
value1 value2

Answer

Beta picture Beta · Jun 8, 2011

You probably shouldn't do this; you're breaking the basic pattern of how Make works. But here it is:

action:
        @echo action $(filter-out $@,$(MAKECMDGOALS))

%:      # thanks to chakrit
    @:    # thanks to William Pursell

EDIT:
To explain the first command,

$(MAKECMDGOALS) is the list of "targets" spelled out on the command line, e.g. "action value1 value2".

$@ is an automatic variable for the name of the target of the rule, in this case "action".

filter-out is a function that removes some elements from a list. So $(filter-out bar, foo bar baz) returns foo baz (it can be more subtle, but we don't need subtlety here).

Put these together and $(filter-out $@,$(MAKECMDGOALS)) returns the list of targets specified on the command line other than "action", which might be "value1 value2".