gpt4 book ai didi

c - Makefile:为什么带有 % 的 makefile 不起作用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:19:18 27 4
gpt4 key购买 nike

我的 makefile 中的 % 不起作用。

我已经在 ubuntu 16.04 x64 上测试了 makefile。

我的 makefile 代码是:版本 1

CC=gcc
OBJ=main.o
TARGET:=main
.PHONY: clean
all : main
# ${OBJ}:%.o:%.c

%.i : %.c
$(info Preprocess: build main.i)
${CC} -E -o $@ $<

%.s : %.i
$(info Compile: build main.s)
${CC} -S -o $@ $<

%.o : %.s
$(info Assemble: build main.o)
${CC} -c -o $@ $<

main : main.o
$(info Link: build main.o)
${CC} -o $@ $^

clean:
rm -f *.o *.out *.s *.i *.asm *.map ${OBJ} main

运行make,终端打印信息:

gcc    -c -o main.o main.c
Link: build main.o
gcc -o main main.o

所以只有最后一条规则(main: main.o) 运行。第一步是自动生成代码 (gcc -c -o main.o main.c)。为什么其他规则没有运行?

然后我修改第三条规则,添加静态模式:版本 2

...
%.i : %.c
$(info Preprocess: build main.i)
${CC} -E -o $@ $<

%.s : %.i
$(info Compile: build main.s)
${CC} -S -o $@ $<

main.o : %.o : %.s
$(info Assemble: build main.o)
${CC} -c -o $@ $<

%: %.o
$(info Link: build main.o)
${CC} -o $@ $^

然后所有规则生效,显示信息:

Preprocess: build main.i
gcc -E -o main.i main.c
Compile: build main.s
gcc -S -o main.s main.i
Assemble: build main.o
gcc -c -o main.o main.s
Link: build main.o
gcc -o main main.o
rm main.i

(为什么运行“rm main.i”?)

我再次修改makefile:版本 3

%.o:%.c
$(info build main.o)
${CC} -c -o $@ $<
main : main.o
$(info Link: build main.o)
${CC} -o $@ $^

可以正常运行。打印消息:

build main.o
gcc -c -o main.o main.c
Link: build main.o
gcc -o main main.o

那么,为什么版本1不能正常工作呢?

最佳答案

它不起作用,因为 make 知道如何从 .c 源构建目标文件 (.o),是一个built-in implicit rule

您可以禁用隐式规则,如果您使用 make -r 运行您的版本 1,它应该按预期运行。

.i 文件被删除,因为它是一个中间文件,默认情况下 make 删除所有中间文件,您可以通过使用 .PRECIOUS 来避免这种情况:一些-文件名

% makefile 中的规则被称为stempattern 规则(不是通配符,它们是另一回事)

您可以使用参数 --debug--debug=all 运行 make 以获得详细日志或更详细的日志

编辑

您还有两个选项可以禁用内置规则并让版本 1 正常工作:

  • 用空规则覆盖特定的内置规则,只需添加 %.o: %.c
  • 禁用所有内置规则添加一个空后缀列表 .SUFFIXES:

If you modify the suffix list, the only predefined suffix rules in effect will be those named by one or two of the suffixes that are on the list you specify

编辑

禁用我过去使用的内置规则的附加选项:

MAKEFLAGS += --no-builtin-rules

关于c - Makefile:为什么带有 % 的 makefile 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56164355/

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