Makefile 11——支持头文件目录指定

时间:2021-07-05 13:51:18

现在,是时候在对应目录放入对应文件了:

 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 #include <stdio.h>
14 #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后报错:

Makefile 11——支持头文件目录指定

这是在构建依赖文件时,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 = crs
10 
11 DIR_OBJS = objs
12 DIR_EXES = $(ROOT)/build/exes
13 DIR_DEPS = deps
14 DIR_LIBS = $(ROOT)/build/libs
15 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 endif
22 
23 ifneq ("$(LIB)", "")
24 LIB := $(addprefix $(DIR_LIBS)/, $(LIB))
25 RMS += $(LIB)
26 endif
27 
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 endif
37 ifeq ("$(wildcard $(DIR_EXES))", "")
38 DEP_DIR_EXES := $(DIR_EXES)
39 endif
40 ifeq ("$(wildcard $(DIR_DEPS))", "")
41 DEP_DIR_DEPS := $(DIR_DEPS)
42 endif
43 ifeq ("$(wildcard $(DIR_LIBS))", "")
44 DEP_DIR_LIBS := $(DIR_LIBS)
45 endif
46 
47 all: $(EXE) $(LIB)
48 
49 ifneq ($(MAKECMDGOALS), clean)
50 include $(DEPS)
51 endif
52 
53 ifneq ("$(INCLUDE_DIRS)", "")
54 INCLUDE_DIRS := $(strip $(INCLUDE_DIRS))
55 INCLUDE_DIRS := $(addprefix -I, $(INCLUDE_DIRS))
56 endif
57 
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) %.c
65     $(CC) $(INCLUDE_DIRS) -o $@ -c $(filter %.c, $^)
66 $(DIR_DEPS)/%.dep: $(DEP_DIR_DEPS) %.c
67     @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) $@.tmp
73 clean:
74     $(RM) $(RMFLAGS) $(RMS)

 

 

 

Makefile 11——支持头文件目录指定

 

这样就完成了支持头文件目录指定