为了学习makefile的编写,我们一步步来学习如何编写这个文件。
从简单到复杂,一步步来,才是学习的正确途径。
首先,在一个目录下,有add.h add.c sub.h sub.c main.c这些文件:
add.h文件:
#ifndef ADD_H #define ADD_H int add(int a, int b); #endif
add.c文件:
#include <stdio.h> #include "add.h" int add(int a, int b) { printf("a : %d, b : %d ", a, b); printf("a + b is %d ", (a+b)); }
sub.h文件:
#ifndef SUB_H #define SUB_H int sub(int a, int b); #endif
sub.c文件:
#include <stdio.h> #include "sub.h" int sub(int a, int b) { printf("a : %d, b : %d ", a, b); printf("a - b is %d ", (a-b)); }
main.c文件:
#include "sub.h" #include "add.h" int main(int argc, char* argv[]) { int a = 3; int b = 4; int c = 0, d = 0; sub(a, b); add(a, b); return 0; }
代码都很简单吧,来看我们的makefile文件如何编写:
objects = main.o add.o sub.o test:$(objects) gcc -o test $(objects) main.o:main.c gcc -c main.c add.o:add.c add.h gcc -c add.c sub.o:sub.c sub.h gcc -c sub.c .PHONY:clean clean: rm test $(objects)
然后我们对此进行一些解释和说明。
makefile的术语:
规则:用于说明如何生成一个或多个目标文件
规则的格式:
targets:prerequisites
command
目标: 依赖
命令
注意:这里的命令需要以[TAB]键开始。
关于伪目标.PHONY
可以参考:http://www.cnblogs.com/chenyadong/archive/2011/11/19/2255279.html
http://www.2cto.com/os/201109/103587.html
all是个伪目标,是所有目标的目标,其功能是编译所有的目标。
.PHONY:all
all:prog1 prog2 prog3 prog4
也可以直接all而省略第一行。
gcc中的-o和-c参数的复习可以参考:http://blog.csdn.net/xiewenbo/article/details/35254899
标签: