针对多个目标的相同规则

针对多个目标的相同规则

本文介绍了Makefile:针对多个目标的相同规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些目标(可以说3个).因此,在生成文件运行之后,我希望有3个可执行文件.

I've some targets (lets say 3). So after the makefile has run, I want to have 3 executable files.

这是我现在所做的:

CC      = gcc
CFLAGS  = -Wall -pedantic -ansi

ECHO  = server_echo
ECHO_O = echo.o

FOO = server_foo
FOO_O = foo.o

ALL = $(ECHO) $(FOO)
ALL_O = ECHO_O FOO_O

all: $(ALL)

$(ECHO): $(ECHO_O)
        $(CC) $(CFLAGS) -o $(ECHO) $(ECHO_O)

$(FOO): $(FOO_O)
        $(CC) $(CFLAGS) -o $(FOO) $(FOO_O)

.PHONY: clean
clean:
        - rm -f $(ALL)
        - rm -f *.o
        - rm -f core

%.o: %.c
        $(CC) $(CFLAGS) -c $<

.PHONY: mci
mci: clean $(ALL)

对于目标$(ECHO)和$(FOO),我有重复的规则.有什么办法可以消除重复吗?像这样:

There I've a duplicate of rules for the targets $(ECHO) and $(FOO). Is there any way, that I can eliminate the duplication? Something like:

for target, target_o in $(ALL), $(ALL_O)
target: target_o
    $(CC) $(CFLAGS) -o target target_o
end for

还是有解决我问题的另一种方法?

Or is there another way to solve my Problem?

感谢您的帮助

推荐答案

没有什么比这容易的了:

Nothing easier:

$(ECHO): $(ECHO_O)
$(FOO): $(FOO_O)

$(ECHO) $(FOO):
        $(CC) $(CFLAGS) -o $@ $^

或者您可以完全使用ECHO_O和FOO_O rel ="noreferrer">静态模式规则:

Or you can do away with the variables ECHO_O and FOO_O entirely with a static pattern rule:

$(ECHO) $(FOO): % : %.o
        $(CC) $(CFLAGS) -o $@ $^

这篇关于Makefile:针对多个目标的相同规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:06