说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/Appendix2/makefiles.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
17.5. make and Makefiles
在本节中,我们讨论 make 命令和 Makefile。我们会给出一些例子,从简单的 Makefile 开始,逐步构建出一个更复杂、更通用的 Makefile(第 17.5.10 节),它适合作为大多数用途的起点。关于编写 Makefile 的更多信息,参见 GNU Make 手册。
In this section we discuss the
makecommand and Makefiles. We present some examples starting from simple Makefile and building up to a more complex and more generic Makefile (Section 17.5.10) that is a good starting point for most uses. For more information about writing Makefiles see the GNU Make Manual.
17.5.1. 关于 make
17.5.1. About make
Unix 的 make 工具简化了程序的编译。用户(或程序)在 Makefile 中写好要执行的规则。用户只需运行 make,make 程序就会从 Makefile 中读入告诉它如何编译程序的规则。
The Unix
makeutility simplifies compiling programs. A user (or a program) writes the Makefile with the rules to execute. A user just runsmakeand themakeprogram reads in rules from theMakefilethat tell it how to compile a program.
make 的一个好处是,只需输入 make 就能执行复杂的命令来构建可执行文件,而不必每次都由用户输入很长的 gcc 命令来构建。较大的程序常常被拆分成由多个 .c 和 .h 文件组成的独立模块。它们还可能要链接多个库,或者把头文件和库文件存放在非标准的位置。所有这些都会让编译变得更复杂,gcc 命令行也更长、更复杂。在这些情况下,在 shell 提示符下手动输入完整的 gcc 命令行既费时又容易出错。例如,下面是一条很长的 gcc 命令行,手动输入它会很繁琐:
One benefit of
makeis that it can execute complex commands to build executable files simply by typingmakeversus the user having to type in longgcccommands to build each time. Larger programs are often split into separate modules consisting of multiple.cand.hfiles. They may also link in multiple libraries, or store header and library files in non-standard locations. All of these make compiling more complicated, andgcccommand lines longer and more complex. In these cases, manually typing the fullgcccommand line at the shell prompt is both time consuming and error prone. For example, here is a longgcccommand line that would be tedious to type by hand:
1 | gcc -Wall -g -I../includes -I. -o mycc emitter.c init.c lexer.c symbol.c parser.c ast.c error.c symbol_table.c codegen.c emitcode.c main.c -L../libs -lmylib -lpthread |
有了 make,用户只需输入 make,就能执行 Makefile 中列出的命令。
With
makethe user simply typesmaketo execute the commands listed in the Makefile.
make 的另一个好处是,它只重新构建那些需要重新构建的东西,即那些依赖于自上次构建以来被修改过的文件的目标文件和可执行文件。对于大型程序,从头开始编译所有东西可能非常耗时,因此 make 只重新构建需要重新构建的东西,可以节省大量的编译时间。
Another benefit of
makeis that it only rebuilds those things that need to be rebuilt — just the object and executable files that depend on files that have been modified since the last time they were built. For large programs, compiling everything from scratch can be very time consuming, and thusmakecan save a lot of compilation time by only rebuilding those things that need to be rebuilt.
用户通常自己编写 Makefile,写好让 make 执行的规则。也有一些程序(例如 CMake 和 GNU Autotools)可以生成 Makefile。它们通常用于构建大型软件,以及方便地支持跨不同系统的编译,包括在特定系统上找到所需的编译器和其他软件、库以及头文件。
A user typically writes the Makefile with the rules for
maketo execute. There are also programs, like CMake and GNU Autotools, that generate Makefiles. These are typically used for building large software and for easily supporting compilation across different systems that includes finding needed compilers and other software, libraries, and header files on a particular system.
17.5.2. 使用 make
17.5.2. Using make
使用 make 的步骤是:
The steps for using
makeare:
- 创建一个 Makefile,列出构建可执行文件的规则。默认情况下,这个文件应当命名为「Makefile」。这只需要做一次,除非程序中加入了新的模块(.c 或 .h 文件),这时就需要更新 Makefile,给现有的规则加上新模块的依赖,或者加入新的规则把它们纳入编译。
- Create a Makefile listing the rules for building the executable. By default the file should be named ‘Makefile’. This only has to be done once, except when new modules (.c or .h files) are added to the program, then the Makefile needs to be updated to add new module dependencies to existing rules or to add new rules to include them in compilation.
- 编辑了程序文件之后,输入 make 重新构建可执行文件: 可以这样输入来执行 Makefile 中某条特定的规则:
1
$ make
例如,要执行1
$ make target_label
rm命令删除下面列出的示例 Makefile 所构建的所有文件,输入:1
$ make clean
After editing program file(s), rebuild the executable by typing make:
1 $ makeA specific rule in the Makefile can be executed by typing:
1 $ make target_labelFor example, to execute the
rmcommand to remove all built files in the example Makefile listed below, type:
1 $ make clean
17.5.3. 创建 Makefile
17.5.3. Creating a Makefile
Makefile 通常以一些变量定义开头,后面是一组用于构建特定目标(通常是构建 .o 文件和可执行文件)的规则(或称目标条目)。每条规则由一个目标标签和一组为该目标运行的相关命令(有时称为配方,recipe)组成。下面是规则的一般格式:
A Makefile typically starts with some variable definitions which are then followed by a set of rules (or target entries) for building specific targets (typically for building .o and executable files). Each rule consists of a target label and a set of associated commands (sometimes called recipes) that are run for the target. The following is the general format of a rule:
1 | # comment |
下面是一个例子:
Here is an example:
1 | # target entry to build program executable from program.o |
原书警示 · make 与空白字符(Make and whitespace characters)
make 对空白字符非常挑剔。例如,在 Makefile 目标条目的命令部分所在行之前的 <tab>,对 make 正确解析目标条目并执行命令部分非常重要。例如,如果你用空格字符代替 <tab>,make 就不能正确解析这个目标条目,也不会运行它的相关命令。
makeis very picky about whitespace characters. For example, the <tab> on the line before the command part of a Makefile target entry is very important formaketo correctly parse the target entry and execute the command part. If, for example, you use space characters in place of the <tab>, thenmakewill not correctly parse the target entry and will not run its associated command.
17.5.4. 一个简单的 Makefile
17.5.4. A Simple Makefile
下面是一个简单的 Makefile 示例,它从单个名为 myprog.c 的 .c 文件构建一个可执行文件:
Here is an example simple Makefile that builds an executable from a single .c file named
myprog.c:
1 | # build an executable named myprog from myprog.c |
输入 make 会触发与 all 目标标签相关联的命令:如果文件 myprog.c 的修改日期比文件 myprog 的修改日期新,或者 myprog 不存在,就运行 gcc -g -Wall -o myprog myprog.c。注意,名字 all 并没有什么特别之处,默认情况下,make 选择 Makefile 中的第一个目标标签来执行。要执行除列出的第一条规则之外的某条特定规则,在 make 命令行上写出目标名即可。例如,make clean 运行 rm myprog 命令,删除之前构建的可执行文件 myprog。
Typing
maketriggers the command associated with thealltarget label to rungcc -g -Wall -o myprog myprog.cif the modification date on the filemyprog.cis newer than the modification date on the filemyprogor ifmyprogdoesn’t exist. Note that the nameallisn’t special, by defaultmakepicks the first target label in the Makefile to execute. To execute a specific rule other than the first one listed in the makefile, list the target name on themakecommand line. For example,make cleanruns therm myprogcommand to remove the previously built executable filemyprog.
在第 17.5.8 节中,我们会展示如何用 Makefile 变量编写这个 Makefile 更通用的版本,只需复制并稍作修改,就能为构建另一个程序创建新的 Makefile。
In Section 17.5.8 we show how to use Makefile variables to write more generic versions of this Makefile—one that can be copied and minimally edited to create a new Makefile for building a different program.
17.5.5. 用于多个源文件的 Makefile
17.5.5. A Makefile for multiple source files
下面是一个从多个 .c 和 .h 文件构建可执行文件的 Makefile 示例。它先把每个 .c 编译成一个 .o 文件,然后把各个 .o 和库链接在一起,构建出可执行文件。由于它为每个 .o 文件列出了依赖关系,如果修改了某一个 .c 文件,就只需要重新构建一个 .o(依赖于被修改的那个 .c 的那个),而不会重新构建所有的 .o 文件。对于由许多 .c 文件组成的较大程序,这是一个特别好的特性,能加快编译时间。
Below is an example Makefile for building an executable from multiple
.cand.hfiles. It first compiles each.cinto a.ofile, and then links the.oand libraries together to build the executable. Because it lists dependencies for each.ofile, if one.cfile is modified only one.oneeds to be rebuilt (the one that is dependent on the modified.c) and it does not rebuild all.ofiles. This is a particularly nice feature that speeds up compile time for larger programs consisting of many.cfiles.
1 | # Example Makefile for a program with many .c modules |
第一次运行 make 之后,如果修改了 counter.c 文件,那么下次运行 make 时,只会执行下面这两条规则(因为它们依赖于 counter.c 或 counter.o):
After running
makethe first time, if thecounter.cfile is modified, then on the next run ofmake, only these two rules are executed (due to their dependency oncounter.corcounter.o):
1 | counter.o: counter.c counter.h |
在第 17.5.9 节和第 17.5.10 节中,我们会展示如何利用 Makefile 变量、Makefile 隐式规则和自动依赖生成,来编写更通用的 Makefile。第 17.5.10 节中的 Makefile 是一个很好的通用 Makefile,适用于由许多 .c 和 .h 文件构建、并且构建时可能要用到存放在非标准位置的头文件或库的应用程序。
In Section 17.5.9 and Section 17.5.10 we show how to use Makefile variables, implicit Makefile rules, and automatic dependency generation, to write more generic versions of a Makefile. The Makefile in Section 17.5.10 is a good generic Makefile for applications built from many
.cand.hfiles, and that may build with header files or libraries stored in non-standard locations.
17.5.6. make 错误
17.5.6. make Errors
make 的错误一般源于两个原因之一。第一个是 Makefile 本身的语法错误,第二个是编译错误,可能是由于 Makefile 中缺少规则,也可能是由于程序本身的错误。使用 make 时,有时可能很难判断需要修正的是 Makefile 还是程序。
Errors in
makegenerally stem from one of two causes. The first are errors in the syntax of the Makefile itself, and the second are compilation errors either due to missing rules in the Makefile, or due to errors in the program itself. When usingmakeit can sometimes be difficult to determine if you need to fix the Makefile or your program.
Makefile 语法错误会报告出错处在 Makefile 中的行号,帮助你找到语法问题。然而,有一些常见的错误很难看出来,因为它们与空白字符的使用错误有关。这类错误的两个例子是:
Errors in Makefile syntax will be reported with the line number in the Makefile of the error to help you track down the syntax problem. However, there are some common errors that are difficult to see because they are related to errors with use of whitespace characters. Two example of this type are:
- 在目标条目命令部分的开头使用空格字符而不是
<tab>。例如,如果这个目标条目第二行的开头是空格字符而不是<tab>字符,make就无法正确解析这条规则:1
2all: myprog.c
$(CC) $(CFLAGS) $(INCLUDES) -o myprog myprog.c
Using space characters instead of a
<tab>at the start of the command part of a target entry. For example, if there are space characters at the beginning of this target entry’s second line instead of a<tab>character,makecannot correctly parse this rule:
1
2 all: myprog.c
$(CC) $(CFLAGS) $(INCLUDES) -o myprog myprog.c
- 文件名前缀的末尾有多余的空格,而 Makefile 在其他地方会给这个前缀加上不同的后缀来展开。例如:如果
1
2TARGET = myprog
SRC = $(TARGET).cmyprog后面有尾随空白,那么SRC就不是myprog.c,而是类似myprog .c的东西,这不是一个合法的文件名。
Having extra spaces at the end of the prefix of a file name that the Makefile expands in other places by adding different suffixes to. For example:
1
2 TARGET = myprog
SRC = $(TARGET).cIf there is trailing whitespace after
myprog, then instead ofSRCbeingmyprog.cit will be something likemyprog .c, which is not a valid file name.
如果错误出在编译或链接上,原因可能是你的 Makefile 有错,也可能是你的程序有错。导致编译或链接错误的 Makefile 错误的一些例子包括:缺少编译某个 .o 的规则;缺少依赖,没有强制重新编译;没有显式链接所需的某个库;或者缺少编译程序所需的头文件和库位置的包含路径(-I 或 -L)。许多这类错误会以 gcc 错误的形式出现,但需要修正的是 Makefile 而不是程序源代码。
If the error is with compiling or linking, it could be due to errors in your Makefile or due to an error in your program. Some examples Makefile errors that cause compilation or linking errors include: a missing rule to compile a
.o; missing dependencies not forcing re-compilation; missing explicitly linking in a needed library; or missing including paths (-Ior-L) to header file and library locations needed to compile the program. Many of these errors will show up asgccerrors, but require fixes to the Makefile instead of the program source.
下面是帮助你判断需要修正的是 Makefile、源代码还是两者都要修正的一些提示:
Some tips to help you determine if the Makefile, the source code, or both need to be fixed include:
- 作为查看是否缺少依赖的第一步,运行
make clean,然后运行make,从头开始重新构建所有东西。如果这样能成功,说明 Makefile 中缺少某个依赖。
- As a first step to see if you are missing a dependency, run
make cleanand thenmaketo rebuild everything from scratch. If it is successful, a dependency is missing in the Makefile.
- 如果你没有看到需要链接进来的某个
.o文件,问题在于你需要添加一条构建它的规则(也许要更新SRCS定义来包含这个新文件)。
- If you don’t see a
.ofile that you need to link in, the problem is that you need to add a rule to build it (perhaps updating yourSRCSdefinition to include this new file).
- 如果编译器报错说找不到某个
.h文件,这表明你需要更新INCLUDES变量,加入一个形如-I[包含目录的路径]的选项,告诉 make 到哪里去找它们。
- If there is an error with the compiler not being able to find a
.hfile, then this indicates that you need to update yourINCLUDESvariable to add a of the form-I[path to include directory]to tell make where to find them.
- 同样,如果编译器报错说找不到库(这些错误在编译的最后阶段,即链接时,以「未定义」错误的形式出现),你需要更新
LIBDIR或LIBS的定义,加入库的路径(-L),或者在命令行中加入需要链接的、缺失的库(-l)。
- Similarly, if there are errors with the compiler not being able to find libraries (these show up as undefined errors during the final compilation stage, linking), you need to update your
LIBDIRorLIBSdefinitions to include paths to libraries (-L) or to add to the command line any missing libraries that need to be linked in (-l).
- 在某些情况下,如果错误出在 C 源文件中,例如缺少
#include,那么可能需要同时更新 C 源文件和 Makefile 才能修正错误。例如,在 C 源文件中加入一个#include,可能还需要在 Makefile 中更新包含路径(-I),在某些情况下还要更新库路径(-L)并显式链接某个库(-l)。
- In some cases when the error is in a C source file, such as missing
#include, both the C source file and the Makefile may need to be updated to fix the error. For example, adding an#includeto a C source file, may also result in updating the include (-I) path, and in some cases also a library path (-L) and explicitly linking in a library (-l) in the Makefile.
17.5.7. 并行 make
17.5.7. Parallel make
对于由许多 .c 和 .h 文件组成的大型程序,编译可能需要很长时间。其中大部分时间可能花在从每个 .c 文件编译出一个 .o 文件上。编译每个 .o 与编译其他 .o 文件是相互独立的,因此这是一个很好的并行化目标:多个线程或进程可以同时并行地编译不同的 .c 文件。给 make 使用 -j[num] 命令行选项,告诉它一次最多运行 num 个作业,即并行地同时执行 num 个不同的配方。
For large programs consisting of many
.cand.hfiles, compiling can take a long time. Much of the time can be due to compiling a.ofile from each.cfile. Compiling each.ois independent of compiling other.ofiles, and thus this is a good target for parallelization where multiple threads or processes can simultaneously compile a different.cfile in parallel. Using the-j[num]command line option tomaketells it to run up tonumjobs at a time, or to in parallel simultaneously executenumdifferent recipes.
例如,要让 make 并行化、一次执行 12 个配方,输入:
For example, to parallelize
maketo perform 12 recipes at a time type:
1 | make -j12 |
在有 12 个或更多核心的机器上,这会比 make 快大约十二倍。
On a machine with 12 or more cores, this will run about twelve times faster than
make.
译注
这是理想情况下的上限。实际加速比还受目标之间的依赖关系,以及最后链接这类只能串行执行的步骤限制(参见第 14 章的阿姆达尔定律)。
17.5.8. 进阶:一个通用的简单 Makefile
17.5.8. Advanced: A Generic Simple Makefile
我们可以改写第 17.5.4 节中的简单 Makefile,让它更通用。通用的 Makefile 更容易修改后用于另一个程序(用户通常先复制一个现有的 Makefile 再修改,而不是每次都从头开始写)。这个更通用的 Makefile 用 Makefile 变量替换规则中具体的应用程序文件名,使规则对任何程序都通用。定义 Makefile 变量的语法是 <variable_name> = <value>。例如:
We can rewrite the simple Makefile from Section 17.5.4 to make it more generic. A generic Makefile is one that is easier to edit for use for another program (typically users start a new Makefile with a copy of an existing one that they then modify versus writing one from scratch each time). This more generic Makefile replaces the specific application file names in rules with Makefile variables resulting in the rule being generic for any program. The syntax for defining Makefile variables is
<variable_name> = <value>. For example:
1 | # define CC to be the name of the compiler |
定义之后,可以在 Makefile 后面用 $(variable_name) 语法使用这个 Makefile 变量。例如:
Once defined, the Makefile variable can be used later in the Makefile using
$(variable_name)syntax. For example:
1 | # use the value of CC in a target entry: |
下面是前面那个从单个 .c 文件构建可执行文件的简单 Makefile 的一个稍微通用一点的版本。这个更通用的简单 Makefile 用变量指定使用哪个编译器(CC)、要传入的编译器选项(CFLAGS)、.c 源文件的名字(SRCS),以及要构建的程序可执行文件的名字(TARGET)。RM 变量是 Makefile 的一个内置变量,定义为 rm 命令。你可以在 Makefile 中把任何内置变量重新定义为别的东西,从而改变它的值。
Below is an example of a slightly more generic version of the simple Makefile above to build an executable from a single .c file. This more generic version of the simple Makefile specifies variables to indicate which compiler to use (
CC), the compiler flags to pass (CFLAGS, the name of the.csource file (SRCS), and the name of the program executable to build (TARGET). TheRMvariable is a builtin Makefile variable that is defined to be thermcommand. You can change the value of any builtin variables by redefining them to be something else in the Makefile.
使用 Makefile 变量的结果是,Makefile 中从 all: 开始的所有内容都是通用的,适用于任何程序。要构建另一个程序,只需修改 SRCS 和 TARGET 变量。
By using Makefile variables, the result is that everything in the Makefile starting with
all:is generic and will work for any program. Only theSRCSandTARGETvariables need to be changed to build a different program.
1 | # define the compiler: gcc for C programs |
只需把 SRCS 定义为列出各个 c 文件,这个 Makefile 也可以用来从多个 .c 源文件构建可执行文件。例如,如果可执行文件由 myprog.c 和 util.c 两个源文件构建,就把 SRCS 定义为:
This Makefile can also be used for building an executable from more than one
.csource file by just definingSRCSto list eachcfile. For example, if the executable is built from two source filesmyprog.candutil.c, defineSRCSto be:
1 | SRCS = myprog.c util.c |
关于这个 Makefile,需要注意的一点是:只要 SRCS 中列出的任何一个源文件被修改了,它总会从所有源文件重新编译可执行文件(因为有这条依赖:$(TARGET): $(SRCS))。对于可能只由一个或几个 .c 文件组成的小程序,这也许没有问题。不过,我们可以调整 Makefile,让它在某个源文件被修改时只重新构建需要重新构建的部分。为此,我们加入从每个 .c 文件编译出目标文件(.o)的规则,然后通过把各个 .o 文件(以及任何库)链接起来构建可执行文件。
One thing to note about this Makefile is that it always recompiles the executable from all source files listed in
SRCSif any one of them have been modified (because of this dependency:$(TARGET): $(SRCS)). For small programs, that may consist of just one or a few.cfiles, this may be fine. However, we can adjust the Makefile to have it only rebuild parts that need to be rebuilt when a source file is modified. We do this by adding rules to compile object files (.o) from each.cfile, and then to build the executable file from linking the.ofiles (and any libraries) into the executable.
17.5.9. 进阶:一个用于多个文件的通用 Makefile
17.5.9. Advanced: A Generic Makefile for Multiple Files
我们可以利用 Makefile 变量和模式替换规则,把第 17.5.5 节中从多个源文件编译可执行文件的 Makefile 改写成一个更通用的 Makefile。
We can rewrite the Makefile from Section 17.5.5 that compiled an executable from multiple source files as a more generic Makefile by making use of Makefile variables and pattern replacement rules.
注意,原来的 Makefile(第 17.5.5 节中的)里从 .c 构建 .o 文件的那些规则,除了具体的文件名之外都很相似。如果能用一条更通用的、从 .c 文件构建 .o 的规则来简化它们就好了。
Note that the rules for building the
.ofiles from the.cin the orginal Makefile (in Section 17.5.5) are all similar except for the specific file names. It would be nice if we could simplify this with a more generic rule for building.ofrom.cfiles.
一种做法是使用一条模式替换规则,它会为任何由 .c 文件构建的 .o 文件触发。下面是这样一条规则的例子。它使用 makefile 自动变量:$< 表示规则的依赖项(一个 .c 源文件)的名字,$@ 表示目标文件(.o 目标文件)。关于自动变量的更多信息,参见 GNU make 手册。
One way to do this is to use a pattern-replacement rule that is triggered for any
.ofile built from a.cfile. Below is an example of such a rule. It uses makefile automatic variables$<for the name of the dependency of the rule (a.csource file) and$@for the target file (the.oobject file). See the gnu make manual for more information about automatic variables.
1 | # This is a pattern replacement rule for building .o files from their |
这是一条短得多的通用规则,适用于任何 C 程序的 Makefile。
This is a much shorter rule, and a generic rule, that will work for any C Makefile.
不过,我们还能做得更好!由于从 .c 文件编译出 .o 是一种非常常见的构建模式,make 有一条从 .c 文件构建 .o 文件的隐式规则。如果我们想使用这条隐式规则,就不在 makefile 中添加任何从 .c 文件构建 .o 文件的规则。这条隐式规则如下:
However, we can do even better than this! Because compiling a
.ofrom a.cfile is such a common build pattern, make has an implicit rule for building.ofiles from.cfiles. If we want to use this implicit rule, we don’t add any rule for building .o files from .c files to our makefile. The implicit rule is the following:
1 | # make's implicit rule for building .o files from .c: |
这条隐式规则使用了一些有默认值的 makefile 变量,不过这些变量也可以在 Makefile 中重新定义(而且通常都会重新定义):
The implicit rule uses some makefile variables that have default values, but that can also be redefined in the Makefile (and usually are):
CC:定义编译器(我们的 Makefile 把CC定义为gcc)
CC: defines the compiler (our Makefile definesCCto begcc)
CFLAGS:定义编译器选项(我们的 Makefile 把它们定义为-g -Wall,即包含调试信息并打开所有警告)。
CFLAGS: defines compiler flags (our Makefile defines these to be-g -Wallwhich includes debugging information and turns on all warnings).
CPPFLAGS:定义预处理器选项(我们的 Makefile 没有定义)。预处理器是编译器最先运行的部分。它展开所有以#开头的东西,例如#include。这里有关于编译各阶段的更多信息。
CPPFLAGS: defines preprocessor flags (our Makefile doesn’t define any). The preprocessor is the first part of the compiler that runs. It expands anything starting with a#, like#include. Here is some more information about the the phases of compilation.
由于我们有一条构建 $(TARGET) 的规则,它依赖于 $(OBJS),make 就会寻找从源文件(.c 文件)构建目标文件(.o)的规则,如果在 Makefile 中找不到,就使用它的隐式规则。如果隐式规则就够用了,我们就不必在 Makefile 中加入任何构建目标文件的规则!我们只需定义它所使用的 makefile 变量(或者使用其默认定义)。如果我们不喜欢这条隐式规则,就需要用自己的规则来覆盖它。
Because we have a rule for building
$(TARGET)that has a dependency$(OBJS),makewill look for a rule for building object files (.o) from source files (.cfiles), and it if doesn’t find one in the Makefile, it uses its implicit rule. If the implicit rule suffices, we don’t have to include any rule for building object files in our Makefile! Instead we just define the makefile variables it uses (or use its default definitions). If we don’t like the implicit rule, then we need to override it using our own rule.
下面是使用隐式规则来构建 .o 文件的 Makefile 版本(注意,Makefile 中从 OBJS = 开始的所有内容都是通用的!):
The following is a version of the Makefile that uses the implicit rule for building
.ofiles (and note that everything in the Makefile starting withOBJS =is generic!):
1 | # Example Makefile using make's implicit .c:.o rule |
这是一个简短而通用的 Makefile。不过,它有一个更长、不太通用的版本所没有的微妙问题:我们丢失了目标文件对头文件的依赖关系,这意味着如果用户更新了一个头文件,然后输入 make,可执行文件和 .o 文件不会被重新构建,而我们希望它们被重新构建。为了解决这个问题,我们可以在 Makefile 中为 TARGET 和 OBJS 或者为单个目标文件加入额外的依赖:
This is a short and generic Makefile. However, there is one subtle problem with this that we don’t have with the longer less generic version: we have lost the dependencies of the header files on the object files, meaning that if the user updates a header file and types
makethe executable and .o files will not be rebuilt, but we want them to be. To fix this problem, we can add additional dependencies to the Makefile forTARGETandOBJSor for individual object files:
1 | # define a variable to be the set of header files |
得到的 makefile 如下所示:
The resulting makefile looks like:
1 | # Example Makefile with implicit .c:.o rule and header file dependencies |
加入了 .h 文件的依赖之后,对 .c 或 .h 文件的修改都会触发 .o 文件和可执行文件的重新构建。不过,这种解决方法有一个微妙的低效之处。问题出在目标文件对所有源文件和头文件的通用依赖上,这意味着当某个特定的 .h 或 .c 文件被更新时,有些 .o 文件会被不必要地重新构建。例如,如果 counter.h 被更新,scanner.o 也会被重新构建,但其实并不需要。解决办法是在 Makefile 中更明确地列举每个 .o 文件的具体依赖,让依赖关系不那么通用,而是针对每个 .o 文件更加具体。例如,把上面 Makefile 中的 $(OBJS): $(HDRS) $(SRCS) 替换为:
With added dependencies of .h files added, changes to either a .c or a .h file will trigger rebuilding of .o and executable files. There is, however, one subtle inefficiency with this solution. The problem is with the generic dependency of objects on all sources and headers, which means that some .o files will be unnecessarily rebuilt when a specific .h or .c file is updated. For example,
scanner.owill be rebuilt ifcounter.his updated, but it does not need to be. The solution to this is to more explicitly enumerate the specific dependencies on each .o file in the Makefile, making the dependencies less generic and more specific for each.ofile. For example, replace$(OBJS): $(HDRS) $(SRCS)in the above Makefile with:
1 | count.o: count.c count.h |
加入这些具体的依赖会让 Makefile 不那么通用,但它避免了更通用的 $(OBJS): $(HDRS) $(SRCS) 带来的不必要的编译。对于小程序,更通用的解决方法可能就够了,但对于较大的程序,仔细列举每个 .o 文件的依赖很重要,既能避免大量不必要的重新编译,也能确保当某个 .o 文件所依赖的文件被修改时,它会被重新构建。
Adding these specific dependencies makes the Makefile less generic, but it avoids unnecessary compilation with the more generic
$(OBJS): $(HDRS) $(SRCS). For small programs the more generic solution might be fine, but for larger programs carefully enumerating the dependencies for each .o file is important to avoid a lot of unnecessary re-compilation, and also to ensure that a .o file is rebuilt when a file it depends on is modified.
正因为如此,有一些方法可以为每个 .o 文件(以及每个可执行文件)自动生成完整的依赖集合。对于由许多源文件和头文件构建程序的 Makefile 来说,为了确保文件被修改时能正确编译,使用自动生成依赖的工具几乎是必不可少的。makedepend 就是这样一个工具,它检查 .c 和 .h 文件,并把依赖关系加到 Makefile 的末尾。另一种方法是使用 gcc 的 -MD(make dependencies,生成依赖)预编译选项生成依赖文件(.d),并在 Makefile 中包含这些文件。
Because of this, there are ways to automatically generate a full set of dependencies for each .o file (and for each executable). Using automatic dependency generating tools is almost necessary for Makefiles for building programs from many source and header files in order to ensure correct compilation when a file is modified. One such tool is
makedepend, which examines .c and .h files and adds dependencies to the end of a Makefile. Another is to use the gcc-MD(make dependencies) precompiler flag to generate dependency files (.d) and to include these files in the Makefile.
17.5.10. 进阶:一个通用的、功能齐全的 Makefile
17.5.10. Advanced: A Generic Featureful Makefile
我们最后一个 makefile 示例是一个通用的、通用目的的 makefile,它包含编译 C 程序常用的一组更完整的 Makefile 变量,还演示了一些更高级的语法和功能,具体包括:
Our last makefile example is a generic general-purpose makefile that includes a more complete set of commonly used Makefile variables for compiling C programs, and it also demonstrates some more advanced syntax and features, specifically:
- 链接库(
-l)
- linking in libraries (
-l)
- 定义链接路径和包含路径(
-L和-I),以找到不在默认位置的库文件和头文件。
- defining link and include paths (
-Land-I) for finding library and header files that are not in default locations.
- 自动生成文件依赖规则(
-MD),并把它们包含到 makefile 中(include)。
- auto generating file dependency rules (
-MD) and including them in a makefile (include).
这也是一个很好的 Makefile 示例,可以复制并修改后供你自己使用
This is also a good example Makefile to copy and edit for your own use
一般来说,C 程序会隐式地链接许多库,但有时还需要用 -l 编译选项显式地链接其他库。gcc 编译器在默认位置查找库代码,但对于不在这些位置的库,需要在 gcc 命令行中显式地写出链接路径。这些路径用 -L 加到 makefile 中。同样,头文件也可能位于非标准的位置,这时 Makefile 需要指定一个指向包含它们的位置的包含文件路径定义。包含路径用 -I 给出。
In general, C programs have many libraries implicitly linked into them, but sometimes other libraries need to be explicitly linked in using the
-lcompiler flag. Thegcccompiler looks in default locations for library code, but for libraries that are not in those locations, a link path needs to be explicitly included in thegcccommand line. These are added to the makefile using-L. Similarly, header files also may be located in non-standard locations, and then the Makefile needs to specify an include file path definition to the location containing them. Include paths are given using-I.
最后,对于有多个 .c 和 .h 文件的程序,自动生成依赖是很有用的。在这个例子中,我们使用 gcc 的 -MD(make dependencies)预编译选项(加到 CPPFLAGS 的定义中)。它在编译的预处理阶段(第一个阶段)为每个 .o 文件创建相应的依赖文件(.d)。然后把这些依赖文件包含到 Makefile 中(include)。.d 文件对 .c 文件有隐式的依赖,所以如果修改了一个 .c 文件,它的 .o 和 .d 都会重新生成。此外,-MP 选项通常与 -MD 选项一起使用,它能在头文件被重命名时抑制错误。
Finally, for a program with multiple
.cand.hfiles, it is useful to automatically generate dependencies. In this example we use thegcc-MD(make dependencies) precompiler flag (added to theCPPFLAGSdefinition). It creates dependency files (.d) associated with each.ofile during the preprocessing phase of compilation (the first phase). These dependency files are then included in the Makefile (include). There is an implicit dependency of.dfiles on.cfiles, so if a.cfile is modified both its.oand.dare regenerated. Also, the-MPflag is typically used with the-MDflag, which suppresses errors if header files are renamed.
下面是得到的 Makefile,它是一个很好的通用 makefile,可以复制并修改后供你自己使用:
Here is the resulting Makefile, which is a good generic makefile to copy and modify for your own use:
1 | # Example Makefile to copy and edit for your own use |
INCLUDES 变量定义了搜索路径,用来查找把 .c 编译成 .o 时需要的 .h 文件。只有当 .h 文件不在当前工作目录中、也不在 gcc 默认检查的位置时,才需要指定这个路径。
The
INCLUDESvariable defines paths to search to find.hfiles that are needed to compile.cfiles to.ofor any.h. The path only needs to be specified if.hfiles are not in the current working directory or in locations thatgccchecks by default.
在编译的链接阶段,编译器链接数学库 -lm 以及由 LIBS 变量定义的本地库 -lmylib,它依据 LFLAGS 变量中指定的搜索路径定义找到这个库。只有在库文件不在 gcc 默认自动搜索的位置时,才需要指定路径。
During the linking phase of compilation, the compiler links the math library
-lmand a local library-lmylibdefined by theLIBSvariable that it finds given the library path definitions in theLFLAGSvariable specifying paths to search. The path only needs to be specified in cases where the library file is not in locations thatgccautomatically searches by default.
使用这个 makefile 运行 make,会先为每个 .c 文件生成 .d 文件,因为我们把 CPPFLAGS 定义为包含 **-MD**,即生成依赖文件。如果你运行 ls,就会看到这些 .d 文件:
Running
makeusing this makefile will first generate.dfiles for each.cfile because we defineCPPFLAGSto have-MD, which means make dependency files. If you runlsyou will see these.dfiles:
1 | $ make |
依赖文件在 Makefile 的最后一行被包含进来:
The dependency files are included in the Makefile in the last line:
1 | -include $(SRCS:%.c=%d) |
这里使用了一个后缀替换规则(SRC:%.c=%d)来指定包含每一个 .d 文件,include 前面的 - 在 .d 文件尚不存在时抑制错误信息。更多细节参见 microHOWTO 上的自动生成 makefile 依赖。
This uses a suffix replacement rule (
SRC:%.c=%d) to specify including every.dfile, and the-beforeincludesuppresses error messages if the.dfile doesn’t already exist. For more details, see automatically generate makefile dependencies from microHOWTO.
译注 · 少了一个点
上一行代码中的 $(SRCS:%.c=%d) 应为 $(SRCS:%.c=%.d)。按原写法,myprog.c 会被替换成 myprogd 而不是 myprog.d,于是生成的依赖文件永远不会被包含进来(而且由于前面有 -,这个错误不会有任何提示)。译者用 GNU Make 验证:SRCS = myprog.c util.c 时,$(SRCS:%.c=%d) 展开为 myprogd utild,$(SRCS:%.c=%.d) 才展开为 myprog.d util.d。
这个 Makefile 还使用了 make 的内置规则来从 .c 文件构建 .o 文件:
This Makefile also uses make’s built-in rule to build
.ofiles from.cfiles:
1 | .c.o: |
由于我们把 CPPFLAGS 设为包含 INCLUDES 以及创建 .d 依赖文件的命令选项,所以可以使用内置规则。
Because we set
CPPFLAGSto include theINCLUDESas well as the command options to create the.ddependency files, we can use the built-in rule.
如果我们没有把 INCLUDES 加到 CPPFLAGS 中,就可以在 Makefile 中用我们自己的规则覆盖内置规则(有时确实需要像这样覆盖内置命令,但这里并不是这种情况):
If we didn’t add
INCLUDEStoCPPFLAGS, then we could override the built-in rule in the Makefile with our own (sometimes it is necessary to override a built-in command like this, but this is not an example where it is):
1 | ... |
17.5.11. 进阶:Makefile 生成器
17.5.11. Advanced: Makefile Generators
对于非常大的程序,尤其是可能安装在不同系统上的软件,使用一个为特定系统生成 Makefile 的程序,会让管理不同的构建目标容易得多。GNU Automake(GNU Autotools 库的一部分)和 CMake 是 makefile 生成程序的两个例子。两者都从配置文件中读取用户的规格说明,在特定系统上查找库并建立依赖关系,然后为该系统自动生成 Makefile。我们在这里不讨论它们中的任何一个,但我们的参考资料一节中有指向它们的更多信息的链接。
For very large programs, and particularly for software that may be installed on different systems, using a program that generates a Makefile for a particular system makes managing different build targets considerably easier. GNU Automake (part of GNU Autotools library) and CMake are two examples of makefile generating programs. Both take user-specifications in a config file to find libraries and create dependencies on specific systems and auto generate Makefiles for that system. We don’t discuss either here, but our references section has links to more information about both.
17.5.12. 参考资料
17.5.12. References
下面是使用 make 和编写 makefile 的几个参考资料:
Here are a few references for using make and writing makefiles:
- gnu.org 上的 GNU Make 手册。
- the GNU Make Manual from gnu.org.
- microHOWTO 上的自动生成 makefile 依赖
- automatically generate makefile dependencies from microHOWTO
- Aniket Bhattacharyea 的理解和使用 Makefile 选项
- Understanding and Using Makefile flags by Aniket Bhattacharyea
- gnu.org 上的 GNU Automake。
- GNU Automake from gnu.org.
- cmake.org 上的 CMake。
- CMake from cmake.org.