现在,是时候在对应目录放入对应文件了:
1 /× foo.h */ 2 3 #ifndef __FOO_H 4 #define __FOO_H 5 6 void foo(void) 7 8 #endif/*__FOO_H*/ 9 10 11 /* foo.c */12 13 #include14 #include "foo.h"15 void foo(void)16 {17 printf("This is foo()!\n");18 }19 20 /* main.c */21 22 #include "foo.h"23 int main(void)24 {25 return 0;26 }
执行make后报错:
这是在构建依赖文件时,gcc因为找不到foo.h而报错。那是因为foo.h和foo.c放在不同的目录中,这样需要使用gcc的 -I 选项,指定包含路径,所以,更改后的Makefile如下:
1 .PHONY: all clean 2 3 MKDIR = mkdir 4 RM = rm 5 RMFLAGS =-rf 6 7 CC = gcc 8 AR = ar 9 ARFLAGS = crs10 11 DIR_OBJS = objs12 DIR_EXES = $(ROOT)/build/exes13 DIR_DEPS = deps14 DIR_LIBS = $(ROOT)/build/libs15 DIRS = $(DIR_OBJS) $(DIR_EXES) $(DIR_DEPS) $(DIR_LIBS)16 RMS = $(DIR_OBJS) $(DIR_DEPS)17 18 ifneq ("$(EXE)", "")19 EXE := $(addprefix $(DIR_EXES)/, $(EXE))20 RMS += $(EXE)21 endif22 23 ifneq ("$(LIB)", "")24 LIB := $(addprefix $(DIR_LIBS)/, $(LIB))25 RMS += $(LIB)26 endif27 28 SRCS = $(wildcard *.c)29 OBJS = $(SRCS:.c=.o)30 OBJS := $(addprefix $(DIR_OBJS)/, $(OBJS))31 DEPS = $(SRCS:.c=.dep)32 DEPS := $(addprefix $(DIR_DEPS)/, $(DEPS))33 34 ifeq ("$(wildcard $(DIR_OBJS))", "")35 DEP_DIR_OBJS := $(DIR_OBJS)36 endif37 ifeq ("$(wildcard $(DIR_EXES))", "")38 DEP_DIR_EXES := $(DIR_EXES)39 endif40 ifeq ("$(wildcard $(DIR_DEPS))", "")41 DEP_DIR_DEPS := $(DIR_DEPS)42 endif43 ifeq ("$(wildcard $(DIR_LIBS))", "")44 DEP_DIR_LIBS := $(DIR_LIBS)45 endif46 47 all: $(EXE) $(LIB)48 49 ifneq ($(MAKECMDGOALS), clean)50 include $(DEPS)51 endif52 53 ifneq ("$(INCLUDE_DIRS)", "")54 INCLUDE_DIRS := $(strip $(INCLUDE_DIRS))55 INCLUDE_DIRS := $(addprefix -I, $(INCLUDE_DIRS))56 endif57 58 $(DIRS):59 $(MKDIR) $@60 $(EXE): $(DEP_DIR_EXES) $(OBJS) 61 $(CC) -o $@ $(filter %.o, $^)62 $(LIB): $(DEP_DIR_LIBS) $(OBJS)63 $(AR) $(ARFLAGS) $@ $(filter %.o, $^)64 $(DIR_OBJS)/%.o: $(DEP_DIR_OBJS) %.c65 $(CC) $(INCLUDE_DIRS) -o $@ -c $(filter %.c, $^)66 $(DIR_DEPS)/%.dep: $(DEP_DIR_DEPS) %.c67 @echo "Creating $@ ..."68 @set -e ; \69 $(RM) $(RMFLAGS) $@.tmp ; \70 $(CC) $(INCLUDE_DIRS) -E -MM $(filter %.c, $^) > $@.tmp ; \71 sed 's,\(.*\)\.o[ :]*,objs/\1.o $@: ,g' < $@.tmp > $@ ; \72 $(RM) $(RMFLAGS) $@.tmp73 clean:74 $(RM) $(RMFLAGS) $(RMS)
这样就完成了支持头文件目录指定