Makefile 简明教程
Why Makefile?
编译源代码文件可能很累,尤其当您必须包含多个源文件并每次编译时都输入编译命令时。Makefile 是简化此任务的解决方案。
Compiling the source code files can be tiring, especially when you have to include several source files and type the compiling command every time you need to compile. Makefiles are the solution to simplify this task.
Makefile 是一种特殊格式的文件,它帮助自动构建和管理项目。
Makefiles are special format files that help build and manage the projects automatically.
例如,假设我们有以下源文件。
For example, let’s assume we have the following source files.
-
main.cpp
-
hello.cpp
-
factorial.cpp
-
functions.h
main.cpp
main.cpp
以下是 main.cpp 源文件的代码 −
The following is the code for main.cpp source file −
#include <iostream>
using namespace std;
#include "functions.h"
int main(){
print_hello();
cout << endl;
cout << "The factorial of 5 is " << factorial(5) << endl;
return 0;
}
hello.cpp
hello.cpp
下面给出的代码为 hello.cpp 源文件 −
The code given below is for hello.cpp source file −
#include <iostream>
using namespace std;
#include "functions.h"
void print_hello(){
cout << "Hello World!";
}
factorial.cpp
factorial.cpp
factorial.cpp 代码如下 −
The code for factorial.cpp is given below −
#include "functions.h"
int factorial(int n){
if(n!=1){
return(n * factorial(n-1));
} else return 1;
}
functions.h
functions.h
fnctions.h 代码如下 −
The following is the code for fnctions.h −
void print_hello();
int factorial(int n);
编译文件并获得可执行文件的简单方法是运行命令 −
The trivial way to compile the files and obtain an executable, is by running the command −
gcc main.cpp hello.cpp factorial.cpp -o hello
此命令生成 hello 二进制文件。在此示例中,我们只有四个文件,并且我们知道函数调用的顺序。因此,键入上述命令并准备最终二进制文件是可行的。
This command generates hello binary. In this example we have only four files and we know the sequence of the function calls. Hence, it is feasible to type the above command and prepare a final binary.
但是,对于拥有数千个源代码文件的较大型项目,维护二进制版本会变得很困难。
However, for a large project where we have thousands of source code files, it becomes difficult to maintain the binary builds.
make 命令允许您管理大型程序或程序组。当您开始编写大型程序时,您会注意到重新编译大型程序所需的时间比重新编译小型程序所需的时间长。此外,您会注意到您通常只处理程序中的一个小部分(例如,一个函数),并且剩余的大部分程序保持不变。
The make command allows you to manage large programs or groups of programs. As you begin to write large programs, you notice that re-compiling large programs takes longer time than re-compiling short programs. Moreover, you notice that you usually only work on a small section of the program ( such as a single function ), and much of the remaining program is unchanged.
在后续部分,我们将了解如何为我们的项目准备 makefile。
In the subsequent section, we see how to prepare a makefile for our project.