Makefile-清洁时如何隐藏“无此文件或目录”错误?

Mys*_*uff 2 c makefile

我正在创建一个C项目作为作业。除源文件外,它还必须包含一个Makefile,该文件必须使用命令“ make”来编译可执行文件“ solution”,以及另一个使用命令“ make debug”来编译带有附加“ -g”参数的可执行文件“ solution.gdb”。为此,我决定制作一组单独的对象文件(“ * .do”文件)。

但是,“ make clean”命令必须从目录中删除所有对象和可执行文件。仅在使用一个命令(“ make”或“ make debug”)之后,当我尝试使用“ make clean”命令时,就会出现问题,因为它试图删除不存在的文件。

错误消息示例:

rm solution.o tree.o list.o commands.o solution.do tree.do list.do commands.do solution solution.gdb
rm: cannot remove 'solution.o': No such file or directory
rm: cannot remove 'tree.o': No such file or directory
rm: cannot remove 'list.o': No such file or directory
rm: cannot remove 'commands.o': No such file or directory
rm: cannot remove 'solution': No such file or directory
Makefile:30: recipe for target 'clean' failed
make: [clean] Error 1 (ignored)
Run Code Online (Sandbox Code Playgroud)

是否可以修改“清洁”说明,所以这些错误不会出现?还是以完全其他的方式来做更好?

在此先感谢您提供所有答案。

生成文件:

CC = gcc
CFLAGS = -Wall -Werror -Wextra
DEBUG_CFLAGS = -g $(CFLAGS)

sources = solution.c tree.c list.c commands.c
objects = $(sources:.c=.o)
debug_objects = $(sources:.c=.do)

solution: $(objects)
    $(CC) -o $@ $^

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

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

solution.o solution.do: tree.h commands.h

commands.o commands.do: tree.h commands.h

tree.o tree.do: list.h tree.h

.PHONY: debug
debug: $(debug_objects)
    $(CC) -o solution.gdb $^

.PHONY: clean
clean:
    -rm $(objects) $(debug_objects) solution solution.gdb
Run Code Online (Sandbox Code Playgroud)

dbu*_*ush 5

使用-f选项rm。该选项告诉rm您忽略不存在的文件,并且不提示您进行确认。

clean:
    rm -f $(objects) $(debug_objects) solution solution.gdb
Run Code Online (Sandbox Code Playgroud)