How to pass argument to Makefile from command line?

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”.

Leave a Comment