makefile编写

make:工程集成的程管理器
makefile,Makefile:同时存在时先调用makefile
make时调用Makefile脚本

有这么几个文件main.c,t1.c,t1.h t2.c,t2.h

//main.c
#include <stdio.h>

#include "t1.h"
#include "t2.h"

int main(){
    t1();
    t2();
    return 0;
}
//t1.c
#include <stdio.h>
#include "t1.h"

void t1(){
    printf("%s\n",__FUNCTION__ );
}
//t1.h
#ifndef T1_H__
#define T1_H__

void t1(void);

#endif
//t2.c
#include <stdio.h>
#include "t2.h"

void t2(){
    printf("%s\n",__FUNCTION__ );
}
//t2.h
#ifndef T2_H__
#define T2_H__

void t2(void);

#endif

原始点的makefile写法

mytool:main.o t1.o t2.o
    gcc main.o t1.o t2.o -o mytool
main.o:main.c
    gcc main.c -c -Wall -g -o main.o
t1.o:t1.c
    gcc t1.c -c -Wall -g -o t1.o
t2.o:t2.c
    gcc t2.c -c -Wall -g -o t2.o
clean:
    rm *.o mytool -rf

t1.c里可以不引用t1.h但是必须得有stdio.h

改版

$(RM)=rm -f

 注意 用变量替换时要$(),括号不可省略

第三版本makefile

用$^代替上句中的被依赖的文件,用$@代替目标文件
OBJS=main.o t1.o t2.o
CC=gcc
CFLAGS+=-c -Wall -g

mytool:$(OBJS)
    $(CC) $^ -o $@
main.o:main.c
    $(CC) $^ $(CFLAGS) -o $@
t1.o:t1.c
    $(CC) $^ $(CFLAGS) -o $@
t2.o:t2.c
    $(CC) $^ $(CFLAGS) -o $@
clean:
    $(RM) *.o mytool -r

第四版
%通配符 同一行代表同一含义

OBJS=main.o t1.o t2.o
CC=gcc
CFLAGS+=-c -Wall -g

mytool:$(OBJS)
    $(CC) $^ -o $@
%.o:%.c
    $(CC) $^ $(CFLAGS) -o $@
clean:
    $(RM) *.o mytool -r