Passing script arguments to a Makefile target

I've many times wondered how I could build a Makefile that would accept arguments to pass to the command invoked by the build target. It turns out to be relatively easy.

There is a make variable called MAKECMDGOALS that contains the list of possible build targets. We can filter-out any of those from the arguments passed to make (as referenced by $@) to get a list of command arguments to pass on to our program.

###!make
SHELL := /bin/bash

.PHONY: hello

default: help

hello:  # Hello world
	@echo "Hello," $(filter-out $@,$(MAKECMDGOALS))


%: # catch-all target to ignore argument "targets"
	@: # no-op

From here, if I invoke make hello world, it will spit out Hello, world.

But what about if you want to pass a flag or option? Add a -- before any flags or options so that make won't treat them as its own options. (That said, I've had limited success with this.

References

I learned this technique via a blog post on CodeGenes.