我从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我在所有内容之前执行,所以没有依赖文件将存在。
-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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句