Makefile的简洁模版

  博客地址:http://www.cnblogs.com/zengjianrong/p/4184854.html 

  为了方便编译零碎的测试代码,在代码的存放目录编辑了一个Makefile,添加新代码文件后,通过make dep&&make all(如果只是修改代码且修改内容不涉及头文件,则只需make all),可以直接得到最终的执行文件。

  流程:1. 遍历当前目录下的“*.c”文件,将其依赖关系保存到depend_file

     2. 将depend_file添加到Makefile里面,调用gcc进行编译。

  优势:不需要添加代码文件名到Makefile中,相关的库文件,编译选项可以统一修改。

CC      := gcc
SRC_PATH    := $(shell pwd)
SRCS        := $(shell find $(SRC_PATH) -name "*.c")
DEP     := $(patsubst %.c,%,$(SRCS))
OBJS        := $(notdir $(patsubst %.c,%.o,$(SRCS)))
CFLAGS      := -g
LIBS        := -lpthread

all:$(OBJS)

$(OBJS):%.o:
    @echo '********************** $< **************'
    $(CC) $(CFLAGS) $(LIBS) $< -o $@
    @echo ''

.PHONY:clean
clean:
    rm -rf *.o
    @echo ''

.PHONY:dep
dep:
    @cat </dev/null >depend_file
    @echo >>depend_file
    @echo '********************** zjr dependency **************'
    for name in $(DEP);
        do $(CC) $(CFLAGS) -MM $$name".c" >temp.txt;
            sed s/`basename $$name".o"`/`basename $$name".o"`/g temp.txt >>depend_file; 
        done;
    @rm -f temp.txt
    @echo ''

-include depend_file            
原文地址:https://www.cnblogs.com/zengjianrong/p/4184854.html