初识makefile

make是常用的一个管理工程编译的工具
其基本用法是:
1、make,使用makefile作为规则文件
2、make -f mf,使用mf作为makefile
3、make all,make clean 指定目标
4、make CPP=g++ 宏定义替换

make的重点在makefile的内容

0、基本格式

# comment
target: dependency
	rule
若target时间比dependency早,则根据rule生成target
注:rule前面是tab,不是空格

1、简单的makefile

hello.exe: hello.cpp
    g++ -o hello.exe hello.cpp
 2、宏 macro
使用宏可以方便替换不同的工具

CPP = g++
hello.exe: hello.cpp
    $(CPP) -o hello.exe hello.cpp
这里CPP 就是一个宏定义,make会根据规则把它替换为g++
make自己定义了若干内部宏,常见的有:
$?:比目标的修改时间更晚的那些依赖模块表
$@:当前目标的全路径名。可用于用户定义的目标名的相关行中
$<:比给定的目标文件时间标记更新的依赖文件名
$*:去掉后缀的当前目标名。例如,若当前目标是pro.o,则$*表示pro

    
3、后缀规则 suffix rule
可以使用后缀规则,缩短时间
.SUFFIXES: .exe .cpp
.cpp.exe: # make exe from cpp
    g++ -o $@ $<
hello.exe: hello.cpp

4、默认目标 default target
经常看见make,后面什么也没有指定,说明使用了默认目标
第一个目标就是默认目标

all:
    hello.exe
    test.exe
hello.exe: hello.cpp
    g++ -o hello.exe hello.cpp
test.exe: test.c
    gcc -o test.exe test.c

5、一个完整的例子
# complete example
CPP = g++
CC = gcc
OFLAG = -o
.SUFFIXES: .exe .cpp .c .obj
.cpp.exe:
    $(CPP) $(OFLAG) $@ $<
.obj.exe:
    $(CC) $(OFLAG) $@ $<
.c.obj:
    $(CC) $(OFLAG) $@ -c $<
    
all:
    hello.exe
    test.exe
hello.exe: hello.cpp
test.exe: test.obj
test.obj: test.c

clean:
    del *.exe
    del *.obj

参考:
1、TICPP_VOL1_chapter3
2、http://blog.csdn.net/it_yuan/article/details/8649407

原文地址:https://www.cnblogs.com/xkxjy/p/3672252.html