makefile 是个工程管理器。
make命令执行时,需要一个 Makefile 文件,以告诉make命令需要怎么样的去编译和链接程序。
makefile 格式 :
target: dependency_files
command (在此行开始要按TAB,再写command)
第一步:建立3个文件,包括fun.c ,fun.h,main.c
/*header file */
#include<stdio.h>
extern int max_fun(int x,int y);
extern void copy(char *src,char *dest);
/*fun.c return max number*/
//#include<fun.h>
#include"fun.h"
int max_fun(int x,int y)
{
return x>y?x:y;
}
/*main.c fuction*/
#include<stdio.h>
#include"fun.h"
int main(int argc,char **argv)
{
int a,b;
char src[50],dest[50];
printf("Enetr the number a and b \n");
scanf("%d%d",&a,&b);
int max=max_fun(a,b);
printf("the max number is %d\n",max);
printf("Enetr input the string :");
scanf("%s",src);
// fflush(stdin);
// fgets(src,50,stdin);
copy(src,dest);
printf("copy the string is :%s\n",dest);
return 0;
}
第二步:vi makefile 将以下方法之一复制到makefile下,执行make 会得到 我们想要的目标文件main(可执行文件),运行./main
方法1:
#makefile write
#printf object mainmain:main.o fun.o
gcc main.o fun.o -o main
main.o:main.c fun.h
gcc -c main.c -o main.o
fun.o:fun.c fun.h
gcc -c fun.c -o fun.o
.PHONY :clean
clean:
rm -f main *.o
方法二:
#makefile write
#put main
OBJS=main.o fun.o
CC=gcc
CFLAGS=-c
main:$(OBJS)
#$(CC) $(CFLAGS) -o main
$(CC) $(OBJS) -o main
main.o:main.c fun.h
$(CC) $(CFLAGS) main.c -o main.o
fun.o:fun.c fun.h
$(CC) $(CFLAGS) fun.c -o fun.o
###.PHONY :clean
clean:
rm -f main *.o
方法三:
#makefile auto variable
#put main
OBJS=main.o fun.o
CC=gcc
CFLAGS=-c
main:$(OBJS)
$(CC) $^ -o $@
main.o:main.c fun.h
$(CC) $(CFLAGS) $< -o $@
fun.o:fun.c fun.h
$(CC) $(CFLAGS) $< -o $@
###.PHONY :clean
clean:
rm -f main *.o
方法四:
#makefile NO show guizhe
#put main
OBJS=main.o fun.o
CC=gcc
CFLAGS=-c
main:$(OBJS)
$(CC) $^ -o $@
#main.o:main.c fun.h
# $(CC) $(CFLAGS) $< -o $@
#fun.o:fun.c fun.h
# $(CC) $(CFLAGS) $< -o $@
###.PHONY :clean
clean:
rm -f main *.o
方法五:
#makefile NO show guizhe
#put main
OBJS=main.o fun.o
CC=gcc
CFLAGS=-c
main:$(OBJS)
$(CC) $^ -o $@
###.PHONY :clean
clean:
rm -f $(OBJS) *.o
~ 方法 六:
#makefile mode guizhe
#put main
OBJS=main.o fun.o
CC=gcc
CFLAGS=-c
main:$(OBJS)
$(CC) $^ -o $@
%.o:%.c
$(CC) $(CFLAGS) $< -o $@
###.PHONY :clean
clean:
rm main $(OBJS)
、、、、、、、、、、、、、好用的makefile 、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
方法最好用的:(再增加一个copy.c,在fun.h头文件增加 extern void copy(char *,char *))
#include"fun.h"
void copy(char *src,char *dest)
{
/* int i=0;
* while(*(src+i)!='\0')
//(*dest)++=(*src)++;
*dest++=*src++;//前置++,执行完在加
*dest='\0';
*/
printf("start copy string :\n");
while(*dest++=*src++)
;
printf("copy success\n");
}
#makefile no show guizhe(隐式规则)
#put objects file : main
makefile 如下:
#OBJS=main.o fun.o
OBJS=main.o fun.o copy.o //增加copy.o 就可以了,和.c文件名要一样
CC=gcc
CFLAGS=-c
main:$(OBJS)
$(CC) $^ -o $@ //$^ is all dependency files,$@is object file
#.PHONY :clean
clean:
rm main $(OBJS) // clear main and all .o file