如何使 makefile 使用模式规则?

How to make makefile to use pattern rule?

拥有这个简单的 makefile:

VPATH = include
CC := gcc
CFLAGS := -I include -Wall -pedantic

%: %.o include.o
    $(CC) -o $@ $^

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

当我使用程序名称触发它时(与扩展名为 .c 的源名称相同),我希望触发第一条规则(因为我只提供了一个名称 而没有 扩展)和第二个,因为对于第一个规则,有 %.o 个先决条件,这正是第二个规则。

密码中有这些文件:

client.c  include  makefile  server6.c  server.c

现在如果我make server: 确实如此

gcc -I include -Wall -pedantic    server.c   -o server

也就是说,没有触发第二条规则。没有制作目标文件的步骤,即使目标文件作为先决条件出现在第一条规则中。那怎么可能呢? make 只是忽略了先决条件,并试图根据第一条规则进行 make。如何解决?

这是因为 make 有一个内置规则 %: %.c 并且 make will always choose 一个模式规则可以直接在需要另一个模式规则的模式规则上创建目标:

Note however, that a rule whose prerequisites actually exist or are mentioned always takes priority over a rule with prerequisites that must be made by chaining other implicit rules.

您可以 运行 make -rremove all the built-in rules, or else remove it yourself 添加:

% : %.c

到您的 makefile。

您可以通过运行ning make -p -f/dev/null

查看所有内置规则