Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Makefile - How to hide "no such file or directory" errors while cleaning?

Tags:

c

makefile

I am creating a C project as an assignment. Besides source files, it has to include a Makefile, which has to compile executable "solution" with command "make" and another executable "solution.gdb" complied with extra "-g" parameter with command "make debug". In order to do so, I decided to make separate set of objects file ("*.do" files).

Command "make clean", however, has to remove all objects and executable files from directory. The problem arises when I try to use "make clean" command, after only using one command ("make" or "make debug"), because it tries to remove non-existent files.

Example error message:

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)

Is there away to modify "make clean" instructions, so these errors does not show up? Or is it better to do it in a completely other way?

Thanks in advance for all the answers.

Makefile:

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
like image 574
Mysquff Avatar asked Mar 09 '23 12:03

Mysquff


1 Answers

Use the -f option to rm. That option tells rm to ignore non-existent files and not prompt for confirmation.

clean:
    rm -f $(objects) $(debug_objects) solution solution.gdb
like image 171
dbush Avatar answered Mar 12 '23 02:03

dbush