makefile 的好处—–“自动化编译”
makeile 需要用make 命令工具
make是解释makefile 中的命令的工具
预编译
将.c 文件转化成 .i文件
使用的gcc命令是:gcc –E
编译
将.c/.h文件转换成.s文件
使用的gcc命令是:gcc –S
汇编
将.s 文件转化成 .o文件
使用的gcc 命令是:gcc –c
链接
将.o文件转化成可执行程序
使用的gcc 命令是: gcc -o
makefile 的编写规则:
target : prerequisites
command
target 可以是目标文件 gcc -c 后的.o文件
也可以是最终的可执行文件
command 是shell命令,需要tab键进行开头
makefile 其实是解决文件依赖关系
target 是依赖 prerequisites 的,也就是说只要
prerequistites里面只要有一个比target新的话,
就执行command
下面使用makefile写的插入排序算法:
union.h文件
#include<stdio.h>
#include<stdlib.h>
main.h文件
#include"swap.h"
#include"show.h"
#include"union.h"
main.c文件
#include"main.h"
#include<unistd.h>
#define length 10
int main()
{
int str [length];
int i;
for(i = 0;i< length;i++)
{
str[i] = rand()%100;
}
printf("原数组:\n");
show(str,length);
sleep(2);
int j;
int k;
for(j = 1;j < length ;j++)
{
for(k = j -1;k>= 0 && str[k] > str[k+1];k--)
{
swap(&str[k],&str[k+1]);
}
}
printf("\n");
printf("排序后数组:\n");
show(str,length);
return 0;
}
show.h文件
#include"union.h"
void show(int str[],int length);
show.c 文件
#include"show.h"
void show(int str[],int length)
{
if(NULL == str)
{
printf("str is error");
}
int i;
for(i =0 ; i< length ;i++)
{
printf(" %d",str[i]);
}
return ;
}
swap.h文件
#include<string.h>
#include"union.h"
#ifndef _SWAP_H_
#define _SWAP_H_
void swap(int *a,int *b);
#endif
swap.c文件
#include"swap.h"
void swap(int *a,int *b)
{
int * temp = (int *)malloc(sizeof(int));
*temp = *a;
*a = *b;
*b = *temp;
return ;
}
Makefile文件
inset_sort : main.o swap.o show.o
gcc main.o swap.o show.o -o inset_sort
main.o : main.h union.h main.c
gcc -c main.c
show.o : show.c union.h
gcc -c show.c
swap.o : swap.c swap.h
gcc -c swap.c
clean :
rm inset_sort show.o swap.o main.o
ls