本文提供一个最简单的Makefile的示例。
Makefile规则
Makefile主要作用是来定义编译规则。
具体格式如下:
A makefile consists of “rules” in the following form:
target: dependencies
system command(s)
- target
A target is usually the name of a file that is generated by a program; examples of targets are executable or object files.
A target can also be the name of an action to carry out, such as "clean".- dependencies
A dependency (also called prerequisite) is a file that is used as input to create the target.
A target often depends on several files.
However, the rule that specifies a recipe(食谱) for the target need not have any prerequisites.
For example, the rule containing the delete command associated with the target "clean" does not have prerequisites.- system command(s)
The system command(s) (also called recipe) is an action that make carries out.
A recipe may have more than one command, either on the same line or each on its own line.
Note the use of meaningful indentation in specifying commands;
also note that the indentation must consist of a single <tab> character.
注意: system command(s)必须以<tab> character开始。
示例代码
工程的文件就三个: function.h function.c main.c
其中function.h中定义函数add, function.c中实现函数add, main.c中调用函数add, 用Makefile文件来定义编译规则。
- function.h
#include <stdio.h>
int add(int in_nNumber1, int in_nNumber2);
- function.c
#include "function.h"
int add(int in_nNumber1, int in_nNumber2)
{
return in_nNumber1 + in_nNumber2;
}
- main.c
#include "function.h"
#include <stdio.h>
int main()
{
int i = 4;
int j = 5;
int k = add(i, j);
printf("%d + %d = %d\n", i, j, k);
return 0;
}
- Makefile
main: main.o function.o
main.o: main.c
gcc -o main.o -c main.c
function.o: function.h function.c
gcc -o function.o -c function.c
clean:
rm -f *.o main
注意: gcc行需要加Tab
运行结果:
如何make名称不是Makefile的文件
如何用make命令,make不是名称不是Makefile的文件呢?
默认的情况下,make命令会在当前目录下按顺序找寻文件名为“GNUmakefile”、“makefile”、“Makefile”的文件,找到了解释这个文件。在这三个文件名中,最好使用“Makefile”这个文件名,因为,这个文件名第一个字符为大写,这样有一种显目的感觉。
最好不要用 “GNUmakefile”,这个文件是GNU的make识别的。有另外一些make只对全小写的“makefile”文件名敏感,但是基本上来说,大多数的make都支持“makefile”和“Makefile”这两种默认文件名。
当然,你可以使用别的文件名来书写Makefile,比如:“Make.Linux”,“Make.Solaris”,“Make.AIX”等,如果要指定特定的Makefile,你可以使用make的“- f”和“--file”参数。
如:make -f Make.Linux或make --file Make.AIX。
执行规则:
make -f filename
References:
http://fancyxinyu.blog.163.com/blog/static/18232136620131125641167/