gpt4 book ai didi

c - 使用 makefile 避免不必要的重新编译

转载 作者:行者123 更新时间:2023-11-30 15:23:30 24 4
gpt4 key购买 nike

我正在使用 makefile 和 gcc。每个 c 文件都有一个附带的 header :

main.c main.h
test.c test.h

main.c 包含 main.h 和 test.h

test.c 包含 test.h

我想避免重新编译每个 c 文件。 Makefile 在没有 -B 参数的情况下运行。

我可以手动编写整个 makefile 并指定每个依赖项。编辑 header 时,仅重新编译必要的 c 文件。 test.h 中的编辑将重新编译两个 c 文件,而 main.h 中的更改将仅重新编译 main.c。正如它应该的那样。

当我切换到更自动化的方法时,这不起作用:

OBJ = main.o test.o

%.o: %.c %.h
$(CC) -c -o $@ $<

main: $(OBJ)
$(CC) -o main $(OBJ)

test.h 中的更改只会重新编译 test.c。将 main.c 保留在旧版本中,并保留旧版本的 test.h header 。如果我想使用这种方法,我必须使用 -B 运行 makefile。

我可以手动指定标题:

DEPS = main.h sort.h

%.o: %.c $(DEPS)
$(CC) -c -o $@ $<

然后 main.h 中的更改会重新编译 main.c 和 test.c,后者是不必要的。

如果我有很多文件,则更新 makefile 中的每个更改都很麻烦,并且使用自动化方法会增加编译时间。

是否有更好的解决方案,仅重新编译所需的文件,或者手动指定所有内容是唯一的方法?

最佳答案

您可以使用另一行指定 main.o 的其他依赖项:

OBJ = main.o test.o

main.o: test.h

关于c - 使用 makefile 避免不必要的重新编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28772825/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com