简体   繁体   中英

How can I pass a variable to a rule in a makefile?

I have several projects in a directory and I want to write a Makefile to build any subset or all of these projects. Each project is in a folder named after itself, which contains a Makefile.

How do I execute these Makefiles?

Here is what I tried:

# Define the project names
PROJECT_NAMES := \
    Project_1 \
    Project_2 \
    Project_3

# Define default behaviour
default: all

# Rule to build all projects
all:
    $(foreach project, $(PROJECT_NAMES), $(CURRENT_PROJECT))

# Rule to build single project
.PHONY $(CURRENT_PROJECT)
$(CURRENT_PROJECT):
    $(MAKE) -C $(CURRENT_PROJECT) make

I think this question might have gone for something similar, but it was not answered: How to make a Makefile call another Makefile rules?

Instead of passing arguments, prerequisites/dependencies should be used. Here is how I solved it:

# Define the project names
PROJECT_NAMES := \
    Project_1 \
    Project_2 \
    Project_3

# Define default behaviour
default: all

# Rule to build all projects now depends on building individual projects
all: $(foreach project, $(PROJECT_NAMES), $(project)_build)

# Rule to build a single project
.PHONY: Project_%
Project_%:
    @echo "****** Building $(subst _build,,$@) ******"
    @$(MAKE) -C $(subst _build,,$@) all

When called without parameters, all projects are built. Any combination of individual projects can be built by simply passing the project names to the makefile such as:

make Project_1 Project_3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM