0

In this makefile example:

EXTERNAL_TXT_FILES:= a/A.txt a/b/B.txt a/b/c/C.txt

EXTERNAL_TXT_NAMES:= $(notdir $(EXTERNAL_TXT_FILES))

DEST_TXT_FILES:= $(addprefix txt/, $(EXTERNAL_TXT_NAMES))

.PHONY:all
all: $(DEST_TXT_FILES)

$(DEST_TXT_FILES):
    cp $< $@

txt/A.txt: a/A.txt
txt/B.txt: a/b/B.txt
txt/C.txt: a/b/c/C.txt

one can see that the last three lines are formulaic.

Is there a way to rewrite this Makefile so that the fixed destination elements of the DEST_TXT_FILES can depend on the elements of the EXTERNAL_TXT_FILES from which they are derived without having to explicitly write them out?

For testing:

$ mkdir -p a/b/c txt && rm -f txt/* && touch a/A.txt a/b/B.txt a/b/c/C.txt && make

I was hoping that replacing the last three lines of the makefile with something like this would work:

foreach (FILE, $(EXTERNAL_TXT_FILES), $(addprefix txt/, $(notdir $(FILE))) : $(FILE))
Jamie
  • 7,075
  • 12
  • 56
  • 86

1 Answers1

0

Duplicated: How can I use macros to generate multiple Makefile targets/rules inside foreach? Mysterious behaviour

My solution:

EXTERNAL_TXT_FILES:= a/A.txt a/b/B.txt a/b/c/C.txt

EXTERNAL_TXT_NAMES:= $(notdir $(EXTERNAL_TXT_FILES))

DEST_TXT_FILES:= $(addprefix txt/, $(EXTERNAL_TXT_NAMES))

.PHONY:all
all: $(DEST_TXT_FILES)

define DUMMY_RULE
$(addprefix txt/, $(notdir $(1))): $(1)
endef

$(foreach FILE, $(EXTERNAL_TXT_FILES), $(eval $(call DUMMY_RULE, $(FILE))))

$(DEST_TXT_FILES):
    cp $< $@
Jamie
  • 7,075
  • 12
  • 56
  • 86
  • If you want to learn more ways to do this check the series of blog posts here: http://make.mad-scientist.net/category/metaprogramming/ – MadScientist Sep 25 '18 at 02:41