我从make开始,我正在搜索如何自动生成我的c文件的依赖项,我找到了这段代码:
# pull in dependency info for *existing* .o files
-include $(OBJS:.o=.d)
# compile and generate dependency info
%.o: %.c
gcc -c $(CFLAGS) $*.c -o $*.o
gcc -MM $(CFLAGS) $*.c > $*.d
我不明白的是,当我生成依赖项文件%.d时,我已经构建了%.o文件,那么创建这个依赖项文件是什么意思,以及我之前执行的-include一切都没有依赖文件存在。
答案 0 :(得分:2)
-include
表示包含dep文件(如果存在),但如果不存在则不会失败。
诀窍,这在make
依赖关系跟踪中很常见,就是你的依赖关系实际上是一个过时的构建。如果它们在那里,你包括上次构建的依赖文件。
这不是问题,因为要更改依赖项,必须对目标在上一次构建期间所依赖的内容进行更改 - 所以即使make不知道全新的依赖项,它也知道它有重建目标(并在进程中生成新的依赖文件)。
附录:顺便说一下,gcc和clang有一个-MD
选项,可以在构建.o
时生成依赖文件(默认情况下带有.d
后缀)。这意味着您可以使用隐式规则进行自动依赖关系跟踪,并将Makefile简化为最小值(对于在平面目录中包含.c
个文件的简单项目):
#!/usr/bin/make -f
# name of the binary to build
TARGET = target
CC = gcc
# These flags are used by the implicit rules for C preprocessor flags,
# C compiler flags, linker flags, and libraries to link (-lfoo options)
# -MD in CPPFLAGS means that the implicit rules for .o files will also
# generate a corresponding .d file that contains the dependencies.
# The values here are just examples (thank you, Rear Admiral Obvious!)
CPPFLAGS = -MD -I somewhere/include
CFLAGS = -O2 -g
LDFLAGS = -L somewhere/lib
LDLIBS = -lsomelibrary
# SRCS is a list of all .c files in the directory, the other two are
# pattern substitution expressions that take SRCS and replace the .c with .o
# and .d, respectively
SRCS = $(wildcard *.c)
OBJS = $(SRCS:.c=.o)
DEPS = $(OBJS:.o=.d)
all: $(TARGET)
$(TARGET): $(OBJS)
# Look, Ma, no explicit rules for .o files!
clean:
rm -f $(TARGET) $(OBJS)
.PHONY: all clean
# include dep files (if available).
-include $(DEPS)
答案 1 :(得分:1)
我通常添加虚假目标depend
,如下所示:
depend: $(SOURCES)
makedepend -Y. $(CFLAGS) $^ 2>/dev/null
并及时更新make depend
更新权限。
有关详细信息,请参阅man makedepend
。