我有一个用 GCC 编译的大项目。 我知道通常执行构建应该重建所有不是最新的依赖项,但是我们更改的一些.h文件不会导致重建使用它们的文件. make文件有层次结构,主make文件根据需要包含需要的make文件。 有没有办法确保重建“#include”最近修改的 .h 文件?
最佳答案
您必须确保您的头文件在先决条件中正确列出。对于大型项目,手动执行此操作是不可行的,但 gcc
(或 clang
)和 GNU Make 的组合为您提供了一种强大的自动化方法。
假设您有一些使用模式规则的非常标准的 Makefile:
CC := gcc
CFLAGS := -std=c11 -Wall -Wextra -pedantic
OBJS := main.o module.o
all: program
program: $(OBJS)
$(CC) -o$@ $^
%.o: %.c
$(CC) -c $(CFLAGS) -o$@ $<
clean:
rm -f *.o
.PHONY: all clean
然后您可以使用 GNU Make 的 Makefiles 自动重建功能来包含添加由 gcc
生成的额外先决条件的文件:
CC := gcc
CFLAGS := -std=c11 -Wall -Wextra -pedantic
OBJS := main.o module.o
all: program
program: $(OBJS)
$(CC) -o$@ $^
# rule to create "dependency files", make the dependency file itself
# depend on the same prerequisites
%.d: %.c
$(CC) -MM -MT"$@ $(@:.d=.o)" -MF$@ $(CFLAGS) $<
# include dependency files except for targets not building anything
ifneq ($(filter-out clean,$(MAKECMDGOALS)),)
-include $(OBJS:.o=.d)
endif
# add Makefiles themselves to prerequisites here (with a changed Makefile,
# the only safe thing is to rebuild all):
%.o: %.c Makefile
$(CC) -c $(CFLAGS) -o$@ $<
# remove dependency files on clean
clean:
rm -f *.o *.d
.PHONY: all clean
这只是一个示例,您可以使用这些功能的多种可能性。
关于c - 自动重建依赖关系(makefiles),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46909140/