前言
Makefile是一个文本文件,是GUN make 程序执行时默认读取配置的文件。
一、Makefile的工作原理
{目标文件}:{依赖文件1}{依赖文件2}···
{命令1}
{命令2}
·
·
·
通过一个或多个依赖文件执行成一个目标文件。并且依赖文件之间可以相互嵌套。
二、使用Makefile
1.编写5个.c文件和4个.h文件
1.c
include<stdio.h>
#include"1.h"
int test_1()
{
printf("test_1.......\n");
return 0;
}
1.h
int test_1();
2.c
#include<stdio.h>
#include"2.h"
int test_2()
{
printf("test_2.......\n");
return 0;
}
2.h
int test_2();
3.c
#include<stdio.h>
#include"3.h"
int test_3()
{
printf("test_3.....\n");
return 0;
}
3.h
int test_3();
4.c
#include<stdio.h>
#include"4.h"
int test_4()
{
printf("test_4.....\n");
return 0;
}
4.h
int test_4();
5.c
#include<stdio.h>
#include"1.h"
#include"2.h"
#include"3.h"
#include"4.h"
int main()
{
test_1();
test_2();
test_3();
test_4();
return 0;
}
2.创建编写Makefile文件
Main:1.o 2.o 3.o 4.o 5.o
gcc 5.c 4.c 3.c 2.c 1.c -o Main
1.o:1.c 1.h
gcc -c 1.c
2.o:2.c 2.h
gcc -c 2.c
3.o:3.c 3.h
gcc -c 3.c
4.o:4.o 4.h
gcc -c 4.c
5.o:5.c 1.h 2.h 3.h 4.h
gcc -c 5.c
clean:
rm Main 1.o 2.o 3.o 4.o 5.o
Main为目标文件,*.o文件是他的依赖文件。通过gcc5个.c文件生成可执行文件Main
1.o是目标文件,1.c和1.h是他的依赖文件。通过gcc 1.c生成1.o文件。下同。
最后是Makefile的clean规则,在当前目录下输入make clean再次查看目录会发现可执行文件Main和*.o文件没有了。
3.make
在目录下输入make后生成可执行文件Main,执行该文件。
总结
Makefile可以完美解决每次编译程序的时候都要输入完整的命令和编译文件名以及参数的问题。省去了繁杂的编译命令,节省了时间。