Roberto Aloi
Roberto Aloi

Reputation: 30995

Iterating over a list in a Makefile and getting both values and indexes

In a GNU Makefile, you have a list of items:

OBJECTS = foo bar baz

You want to iterate over the items and you're interested in both the index and the value of each item (foo => 1, bar => 2, baz => 3). What's the idiomatic way of doing this in a Makefile?

Upvotes: 5

Views: 5705

Answers (1)

Beta
Beta

Reputation: 99144

There are several ways to do this, none of them very clean (which is a strong hint that you're trying to do something that isn't really suited to Make), and your particular case may require special handling, but here goes:

OBJECTS = foo bar baz

NLIST = $(shell for x in {1..$(words $(OBJECTS))}; do echo $$x; done)

LIST = $(foreach x,$(NLIST), do_something_with_$(x)_and_$(word $(x),$(OBJECTS)))

Upvotes: 6

Related Questions