[英]Automatic make dependency generation with gcc
New to GNU Make and trying to build a Makefile that automatically generates its dependencies for rebuilding so that the necessary objects get rebuilt and linked upon changing a header file.刚接触 GNU Make 并尝试构建一个 Makefile,它会自动生成用于重建的依赖项,以便在更改头文件时重建和链接必要的对象。
Rather than using .d files I want to have a single file like .depend
so I have a rule that creates the file and include it as a dependency like this (using sed to append obj/
in front of every line)而不是使用 .d 文件,我想要一个像
.depend
这样的单个文件,所以我有一个规则来创建文件并将其作为这样的依赖项包含在内(使用 sed 在每一行前面附加obj/
)
.depend: $(SRC_FILES)
rm -f ./.depend
$(CC) $(CFLAGS) -MM $^ | sed 's/^/$(OBJECT_DIR)\//' >> ./.depend;
include .depend
The problem is, upon building it only compiles the first rule in the .depend
file and then stops with a succession.问题是,在构建时它只编译
.depend
文件中的第一条规则,然后连续停止。 This is very likely a problem with the way I have my rules/targets set up but I can't figure out what's making it stop at the first built object, my file looks like this这很可能是我设置规则/目标的方式有问题,但我无法弄清楚是什么让它在第一个构建的对象处停止,我的文件看起来像这样
BIN_NAME := test
# Compiler
CC := gcc
CFLAGS := -Wall -O3
# Directories
BINARY_DIR := bin
OBJECT_DIR := obj
SOURCE_DIR := src
# Files
SRC_FILES := $(wildcard $(SOURCE_DIR)/*.c)
OBJ_FILES := $(patsubst $(SOURCE_DIR)/%.c,$(OBJECT_DIR)/%.o, $(SRC_FILES))
# Dependencies
.depend: $(SRC_FILES)
rm -f ./.depend
$(CC) $(CFLAGS) -MM $^ | sed 's/^/$(OBJECT_DIR)\//' >> ./.depend;
#include .depend
# Targets
$(OBJECT_DIR)/%.o: $(SOURCE_DIR)/%.c
$(CC) $(CFLAGS) -c $< -o $@
$(BINARY_DIR)/$(BIN_NAME): $(OBJ_FILES)
$(CC) $(CFLAGS) -o $@ $^
clean:
rm $(OBJECT_DIR)/* $(BINARY_DIR)/* .depend
Commenting include .depend
skips generation of the .depend file and outputs the binary properly but only updates when changing a source file as expected when not using dependency gen.注释
include .depend
跳过 .depend 文件的生成并正确输出二进制文件,但仅在不使用依赖项 gen 时按预期更改源文件时才更新。 I want to know what causes this behavior, and the problems with my targets.我想知道是什么导致了这种行为,以及我的目标存在的问题。 The sample
.depend
file looks like this示例
.depend
文件如下所示
obj/message.o: src/message.c src/message.h
obj/hello.o: src/hello.c src/message.h
Read the intro section in the GNU make manual and you will see in the first sentence:阅读 GNU make 手册中的介绍部分,您将在第一句话中看到:
By default, make starts with the first target.
默认情况下,make 从第一个目标开始。
What's the first target in your makefile?你的 makefile 中的第一个目标是什么? Since the
include
comes before any other targets, it's the first target in the include
d file.由于
include
出现在任何其他目标之前,因此它是include
d 文件中的第一个目标。
As Beta says, simply put the include
line at the end of your makefile (or at least, not at the beginning) and your problem will be solved.正如 Beta 所说,只需将
include
行放在 makefile 的末尾(或者至少不是开头),您的问题就会得到解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.