现将项目文件放入各目录中:
huge / code / foo / inc / foo.h
#ifndef __FOO_H
#define __FOO_H
void foo();
#endif
huge / code / foo / inc / foo.c
#include <stdio.h>
#include "foo.h"
void foo()
{
printf("This is foo ()!\n");
}
huge / code / huge / src / main.c
#include "foo.h"
int main()
{
foo();
return 0;
}
运行结果:
$ make
/Makefile/huge/build/make.rule:50: deps / foo.dep:No such file or directory
mkdir deps
Creating deps / foo.dep
foo.c : 2:17: error: foo.h: No such file or directory
make: *** [deps / foo.dep] Error 1
在构建 foo.dep 依赖文件时,gcc 因为找不到 foo.h 而报错并最终导致编译失败,原因是:foo.c 和 foo.h 文件被放在不同的目录中,在编译源文件是需要采用一定的形式告诉编译器到指定的目录中查找头文件,这得用到 gcc 的 -I 选项
huge / build / make.rule
.PHONY : all clean
NKDIR = mkdir
RM = rm
RMFLAG = -rf
CC = gcc
AR = ar
ARFLAG = crs
DIR_OBJS = objs
DIR_EXES = $(ROOT)/build/exes
DIR_DEPS = deps
DIR_LIBS = $(ROOT)/build/libs
DIRS = $(DIR_OBJS) $(DIR_EXES) $(DIR_DEPS) $(DIR_LIBS)
RMS = $(DIR_OBJS) $(DIR_DEPS)
ifneq("$(EXE)", "")
EXE := $(addprefix $(DIR_EXES)/, $(EXE))
RMS += $(EXE)
endif
ifneq("$(LIB)", "")
LIB := $(addprefix $(DIR_LIBS)/, $(LIB))
RMS += $(LIB)
endif
SRCS = $(wildcard *.c)
OBJS = $(SRCS :.c = .o)
OBJS := $(addprefix $(DIR_OBJS)/, $(OBJS))
DEPS = $(SRCS :.c = .dep)
DEPS := $(addprefix $(DIR_DEPS)/, $(DEPS))
ifeq("$(wildcard $(DIR_OBJS))", "")
DEP_DIR_OBJS := $(DIR_OBJS)
endif
ifeq("$(wildcard $(DIR_EXES))", "")
DEP_DIR_EXES := $(DIR_EXES)
endif
ifeq("$(wildcard $(DIR_DEPS))", "")
DEP_DIR_DEPS := $(DIR_DEPS)
endif
ifeq("$(wildcard $(DIR_LIBS))", "")
DEP_DIR_LIBS := $(DIR_LIBS)
endif
all : $(EXE) $(LIB)
ifneq($MAKECMDGOALS, clean)
include $(DEPS)
endif
ifneq($(INCLUDE_DIRS), "")
INCLUDE_DIRS := $(strips $(INCLUDE_DIRS))
INCLUDE_DIRS := $(addprefix -I, $(INCLUDE_DIRS))
endif
$(DIRS) :
$(MKDIR) $@
$(EXE) : $(DEP_DIR_EXE) $(OBJS)
$(CC) -o $@ $(filter %.o, $^)
$(LIB) : $(DEP_DIR_LIB) $(OBJS)
$(AR) $(ARFLAG) $@ $(filter %.o, $^)
$(DIR_OBJS) / %.o : $(DEP_DIR_OBJS) %.c
$(CC) $(INCLUDE_DIRS) -o $@ -c $(filter %.c, $^)
$(DIR_DEPS) / %.dep : $(DEP_DIR_DEPS) %.c
@echo "Creating $@ ..."
@set -e;\
$(RM) $(RMFLAG) $@.tmp;\
$(CC) $(INCLUDE_DIRS) -E -MM $(filter %.c, $^) > $@.tmp;\
sed 's,\(.*\)\.o[ :]*,objs/\1.o $@: ,g' < $@.tmp > $@;\
$(RM) $(RMFLAG) $@.tmp
clean :
$(RM) $(RMFLAG) $(RMS)
huge / code / foo / src / Makefile
EXE =
LIB = libfoo.a
INCLUDE_DIRS = $(ROOT)/code/foo/inc
include $(ROOT)/build/make.rule
huge / code / huge / src / Makefile
EXE = huge.exe
LIB =
INCLUDE_DIRS = $(ROOT)/code/foo/inc
include $(ROOT)/build/make.rule
改动如下:
- 增加了一个用于存放头文件目录的 INCLUDE_DIRS 变量,这个变量可以根据需要存放任意数目的目录
- 当 INCLUDE_DIRS 变量的值不为空时,先采用 strip 函数去除多余的空格,然后再调用 addprefix 为其增加 -I前缀
- 在目标文件生成规则和依赖文件生成规则中增加对 INCLUDE_DIRS 变量的引用,让 gcc 知道去哪里找头文件
运行结果:
$ make
/Makefile/huge/build/make.rule:43: deps / foo.dep:No such file or directory
mkdir deps
Creating deps / foo.dep
mkdir objs
gcc -I/Makefile/huge/code/foo/libs/inc -o objs/foo.o -c foo.c
ar crs /Makefile/huge/build/libs/libfoo.a objs/foo.o
$ ls $ROOT/build/libs
libfoo.a
参考文献:《专业嵌入式软件开发》李云·著
2016年7月5日,星期二