Using Foreach to Create Rules in GNU Make

Created: 2022-04-16T16:10:24-05:00

Return to the Index

This card pertains to a resource available on the internet.

TOOLS:=foo bar

.PHONY: all
all : $(TOOLS)

.PHONY: install $(addprefix install_,$(TOOLS))
install : $(addprefix install_,$(TOOLS))

.PHONY: uninstall $(addprefix uninstall_,$(TOOLS))
uninstall : $(addprefix uninstall_,$(TOOLS))

define TOOL_template
$(1): $($(1)_OBJS)
#commands to build it

install_$(1): $(1)
install -c $(1) $(prefix)/bin/$(1)

uninstall_$(1):
rm $(prefix)/bin/$(1)
endef

$(foreach tool,$(TOOLS),$(eval $(call TOOL_template,$(tool))))

The separate install and uninstall targets are a pattern needed so that parallel jobs function.

NOTE: the 'eval' can probably be removed as others on stack overflow suggest.