Makefile 简明教程

Defining Custom Suffix Rules in Makefile

Make 可以使用 cc -c 针对相应 .c 文件自动创建 .o 文件。 make 中内置这些规则,您可以利用这个优势缩短 Makefile。如果仅在 Makefile 的依赖性行中指示当前目标依赖的 .h 文件, make 会知道已经需要相应的 .c 文件。您不必包含编译器的命令。

Make can automatically create a.o file, using cc -c on the corresponding .c file. These rules are built-in the make, and you can take this advantage to shorten your Makefile. If you indicate just the .h files in the dependency line of the Makefile on which the current target is dependent on, make will know that the corresponding .cfile is already required. You do not have to include the command for the compiler.

这会进一步缩减 Makefile,如下所示 −

This reduces the Makefile further, as shown below −

OBJECTS = main.o hello.o factorial.o
hello: $(OBJECTS)
   cc $(OBJECTS) -o hello
hellp.o: functions.h

main.o: functions.h
factorial.o: functions.h

Make 使用一个名为 .SUFFIXES 的特殊目标,允许您定义自己的后缀。例如,请参考下方给出的依赖性行−

Make uses a special target, named .SUFFIXES to allow you to define your own suffixes. For example, refer the dependency line given below −

.SUFFIXES: .foo .bar

它会告知 make 您将使用这些特殊后缀来制定自己的规则。

It informs make that you will be using these special suffixes to make your own rules.

类似于 make 已知如何根据 .c 文件制作 .o 文件,您可按如下方式定义规则 −

Similar to how make already knows how to make a .o file from a .c file, you can define rules in the following manner −

.foo.bar:
   tr '[A-Z][a-z]' '[N-Z][A-M][n-z][a-m]' < $< > $@
.c.o:
   $(CC) $(CFLAGS) -c $<

第一条规则允许根据 .foo 文件创作 .bar 文件。它基本上会打乱该文件。第二条规则是 make 用来根据 .c 文件制作 .o 文件的默认规则。

The first rule allows you to create a .bar file from a .foo file. It basically scrambles the file. The second rule is the default rule used by make to create a .o file from a .c file.