想象一下,一个项目中有很多源代码文件,如果人工手动编译源代码文件,每次编译都需要在执行命令时输入很多源代码文件,很繁琐。使用makefile可以大大简化编译工作。
makefile是具有一定格式,用于自动构建配置的文件。makefile由make工具读取并执行。例如要编译当前目录,只需在命令行执行 make
。
Makefile名称
Makefile的标准名称是
makefile
或Makefile
,通常make会在当前目录按顺序查找:makefile
或Makefile
,如果没找到,make停止执行。如果makefile不是标准名称,可通过
-f
参数指定Makefile:make -f your-makefile-name
例如,假设我们有以下源代码文件:
- main.cpp
- hello.cpp
- factorial.cpp
- functions.h
main.cpp
#include <iostream>
using namespace std;
#include "functions.h"
int main(){
print_hello();
cout << endl;
cout << "5的阶乘是 " << factorial(5) << endl;
return 0;
}
hello.cpp
#include <iostream>
using namespace std;
#include "functions.h"
void print_hello(){
cout << "Hello World!";
}
factorial.cpp
#include "functions.h"
int factorial(int n){
if(n!=1){
return(n * factorial(n-1));
} else return 1;
}
functions.h
void print_hello();
int factorial(int n);
编译程序可运行命令:
gcc main.cpp hello.cpp factorial.cpp -o hello
这个命令生成hello可执行文件。本例中,只有4个源代码文件,并且我们清楚函数调用的顺序,手工执行编译命令是可行的。
但是,对于有数千个源代码文件的大型项目,手工构建项目会变得非常困难。另外,一个大型项目的完整构建时间往往很长,但实际开发中并不需要每次都完整构建,通常只需重新编译其中的一小部分。这些都可以通过使用Makefile解决。