程序结构:
./include/ 包含一个.h文件
./src 包含4个.c文件,每个.c都包含./include/中的.h文件
./obj 存放编译生成的文件
makefile代码如下:
=========================================
SrcDir = src/
ObjDir = obj/
IncludeDir = include/
Src = $(wildcard $(SrcDir)*.c)
SrcFile = $(notdir $(Src))
ObjFile = $(patsubst %.c,%.o,$(SrcFile))
Obj = $(addprefix $(ObjDir),$(ObjFile))
CC = gcc
all:main
main:$(Obj)
$(CC) $(CFLAGS) -o main $^
sinclude $(addprefix $(ObjDir),$(SrcFile:.c=.d))
$(ObjDir)%.o:$(SrcDir)%.c
$(CC) -c -I$(IncludeDir) $< -o $(ObjDir)$*.o
$(ObjDir)%.d:$(SrcDir)%.c
set -e;\
$(CC) -MM -I$(IncludeDir) $< |\
sed 's,\($*\)\.o[:]*,$(ObjDir)\1.o $@:,g' > $@
.PHONY:clean test
clean:
set -e;\
rm -f main;\
rm -f $(ObjDir)*.o $(ObjDir)*.d
=====================================================
可实现增量编译.
makefile规则中"目标"和"依赖"路径要写清楚,否则可能会使用隐含规则,或出错.