使用场景:目录下的所有源文件都能生成可执行程序。如在做《C++ Primer》练习时,每个练习都是一个独立的小程序,不必为每个练习编写一个Makefile,也不必为每个练习执行g++编译。
CC :=gcc CFLAGS := -g -Wall SOURCES := $(wildcard *.c) TARGETS := $(patsubst %.c,%,$(SOURCES)) #define a function define MAKE_EACH_SRC_BIN $1:$1.c $(CC) $(CFLAGS) $< -o $@ endef all:$(TARGETS) $(foreach target,$(TARGETS),$(call MAKE_EACH_SRC_BIN $(target))) clean: rm -rf $(TARGETS)
使用场景:可以应对大多数类型的工程,包含多个目录的工程,不必为每个目录编写一个Makefile。自动生成头文件依赖,不必因改变头文件而make clean。
GROOT :=$(shell pwd) PROGRAM := iked SRCDIRS := . ./isakmp ./ikev1 ./crypto SRCEXTS := .c .cc CPPFLAGS := -Wall -Werror -g -m32 CFLAGS := CFLAGS += CXXFLAGS := -I/usr/local/openssl/include CXXFLAGS += -I$(GROOT)/ -I$(GROOT)/isakmp -I$(GROOT)/crypto -I$(GROOT)/ikev1 LDFLAGS := -lpthread -L/usr/local/openssl/lib -lcrypto -ldl LDFLAGS += -m32 #CC = gcc #CXX = g++ #CC = $(CXX) #CFLAGS = $(CXXFLAGS) #RM = rm -f SHELL = /bin/sh SOURCES = $(foreach d,$(SRCDIRS),$(wildcard $(addprefix $(d)/*,$(SRCEXTS)))) OBJS = $(foreach x,$(SRCEXTS), $(patsubst %$(x),%.o,$(filter %$(x),$(SOURCES)))) DEPS = $(patsubst %.o,%.d,$(OBJS)) .PHONY : all objs clean cleanall rebuild all : $(PROGRAM) %.d : %.c @$(CC) -MM -MT ${@:%.d=%.o} -MD $(CXXFLAGS) $< -o $@ %.d : %.C @$(CC) -MM -MT ${@:%.d=%.o} -MD $(CXXFLAGS) $< -o $@ %.d : %.cc @$(CC) -MM -MT ${@:%.d=%.o} -MD $(CXXFLAGS) $< -o $@ %.d : %.cpp @$(CC) -MM -MT ${@:%.d=%.o} -MD $(CXXFLAGS) $< -o $@ %.d : %.CPP @$(CC) -MM -MT ${@:%.d=%.o} -MD $(CXXFLAGS) $< -o $@ %.d : %.c++ @$(CC) -MM -MT ${@:%.d=%.o} -MD $(CXXFLAGS) $< -o $@ %.d : %.cp @$(CC) -MM -MT ${@:%.d=%.o} -MD $(CXXFLAGS) $< -o $@ %.d : %.cxx @$(CC) -MM -MT ${@:%.d=%.o} -MD $(CXXFLAGS) $< -o $@ objs : $(OBJS) %.o : %.c $(CC) -c $(CPPFLAGS) $(CFLAGS) $< -o $@ %.o : %.C $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< -o $@ %.o : %.cc $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< -o $@ %.o : %.cpp $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< -o $@ %.o : %.CPP $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< -o $@ %.o : %.c++ $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< -o $@ %.o : %.cp $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< -o $@ %.o : %.cxx $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< -o $@ $(PROGRAM) : $(OBJS) ifeq ($(strip $(SRCEXTS)), .c) # C file $(CC) -o $(PROGRAM) $(OBJS) $(LDFLAGS) else # C++ file $(CXX) -o $(PROGRAM) $(OBJS) $(LDFLAGS) endif -include $(DEPS) rebuild: clean all clean : @$(RM) $(OBJS) $(DEPS) cleanall: clean @$(RM) $(PROGRAM) $(PROGRAM).exe