Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

linux - For each on target of Makefile variable

I've makefile which looks like follows

apps = app1 app2 app3

all: dir app1 app2 app3 zip cleanup

Now I want to do some loop on the list of apps varible,

something like

`loop on apps

endloop`

Is it possible in makefile to loop on it, I need to do loop on apps varible list

update

lets say this variable(apps) is generated by my program in the make file, which provide for each project diffrent values of apps, sometimes its apps= app1 app2 sometimes its apps= app1 and sometimes can be 20 apps or more apps= app1 app2 appN

How can I iterate on apps varible and do something, for example in each iteration print something like:

now im in `app1`
now im in `app2`
etc

When trying the following

.PHONY: foo
all: foo
APPS = app1 app2 app3 app4
foo : $(APPS)
    for $$f in $(APPS); do echo $$f is here; done

I got following error:

make: *** No rule to make targetapp1', needed by foo'. Stop.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I see you've gone back and forth a bit, so let me just make a comment which may or may not help.

In general you don't write loops inside make recipes, because make itself provides "looping". So when you write a rule like:

all: app1 app2 app3 app4

make will try to build each one of those prerequisites, one at a time. So if you wanted to have a makefile that echoed a line for each entry in the apps variable you would do it like this:

all: $(apps)

$(apps):
        @echo $@

This tells make to start with a target all and try to "build" each of its prerequisites which are the values in the apps variable.

Then you define a rule for how to build the apps, and for each one you say that the rule is echo $@ where $@ is an automatic variable that expands to the currently-building target.

In make, the syntax:

foo bar biz:
        some command

is shorthand for, and identical to, writing:

foo:
        some command
bar:
        some command
biz:
        some command

The crucial thing when writing makefiles is that you think how to write a rule to create one file (target) from zero or more prerequisite files. Then you let make worry about how to connect all those prerequisites together and order them properly.

ETA If you want a special rule for one particular target in a long list held in the $(apps) variable, you can do this:

$(filter-out bar,$(apps)):
        @echo print $@

bar:
        some other command

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...