c - 自动重建依赖关系(makefiles)

标签 c makefile build dependencies

我有一个用 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/

相关文章:

ios - 将表示十六进制值的 NSString 转换为十六进制( @"0d"到 0x0d)

生成文件。如何从编译中排除一个特定文件?

java - 如何跳过多 Maven 模块中的生命周期阶段

c++ - ./configure使用ssldump代码库抛出错误

build - 如何在 vscode 工作区文件夹之间共享任务?

Android Studio 构建失败,因为 "Task ' ' not found in root project 'MyProject' 。”

c - 语音 ip 的服务类型字段集

c - 访问结构成员字符指针

C 读/写文件 - 访问冲突

ant - 如果 makefile 失败则停止 ant 构建