【问题标题】:Why does makefile recompiles everything when a headerfile is changed?为什么在头文件更改时makefile会编译所有内容?
【发布时间】:2019-05-14 13:04:57
【问题描述】:

当头文件改变时,我的 makefile 会重新编译所有内容,我怎样才能让它只重新编译需要的文件? a_functions.c 以 a.h 为例。

每当我更改 .c 文件时,makefile 只会将该文件重新编译为对象。

SHELL=/bin/sh
CC=gcc
CFLAGS=-Wall
OBJECTS=main.o a_functions.o b_functions.o c_functions.o d_functions.o
DEPS=main.h a.h b.h c.h d.h
PROGRAM_NAME=program1
INSTALL_PATH=/usr/local/bin

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

.PHONY: all
all: $(PROGRAM_NAME)

$(PROGRAM_NAME): $(OBJECTS)
    $(CC) $(OBJECTS) -o $(PROGRAM_NAME)

.PHONY: install
install: $(PROGRAM_NAME)
    install -c $(PROGRAM_NAME) $(INSTALL_PATH)/

.PHONY: uninstall
uninstall:
    rm -v $(INSTALL_PATH)/$(PROGRAM_NAME)

.PHONY: clean
clean:
    rm -v $(PROGRAM_NAME) *.o

如果我更改了下面的头文件

$ make
gcc -c -Wall main.c -o main.o
gcc -c -Wall a_functions.c -o a_functions.o
gcc -c -Wall b_functions.c -o b_functions.o
gcc -c -Wall c_functions.c -o c_functions.o
gcc -c -Wall d_functions.c -o d_functions.o
gcc main.o a_functions.o b_functions.o c_functions.o d_functions.o -o program1

当我更改 .c 文件时,会发生这种情况,这也是我想要的所有标题。

$ make
gcc -c -Wall a_functions.c -o a_functions.o
gcc main.o a_functions.o b_functions.o c_functions.o d_functions.o -o program1

希望它是这种方式是常见的做法吗?我将如何更改我的代码来解决问题?

【问题讨论】:

  • DEPS=main.h a.h b.h c.h d.h 然后%.o: %.c $(DEPS) 它给你任何线索吗?

标签: c makefile


【解决方案1】:

您有一条规则,所有从 .c 文件构建的 .o 文件也依赖于 $(DEPS) 的内容

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

其中似乎包含您所有的 .h 文件。

DEPS=main.h a.h b.h c.h d.h

您应该从该规则中删除 $(DEPS) 并专门为每个 .o 文件指定依赖项,如下所示:

a_functions.o: a.h
main.o: a.h b.h

如果您已经安装了它,您可以使用makedepend 来完成“繁重的工作”并为您解决依赖关系并更新您的 Makefile。甚至像这样将其添加为规则

depend:
    makedepend -- $(CFLAGS) -- $(SRCS)

(这需要您定义您拥有的源文件)

【讨论】:

  • 如果您的项目足够大,需要付出额外的努力,那么管理先决条件的方法要比makedepend 好得多。但是它们确实需要 makefile 中的一些复杂性和具有足够功能的编译器(但是,gcc 和 clang 都可以做到这一点)。如果您有兴趣,请参阅例如 make.mad-scientist.net/papers/…
猜你喜欢
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-11
  • 1970-01-01
  • 2018-05-29
相关资源
最近更新 更多