5

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
Mysquff
  • 293
  • 4
  • 11
  • you may add -f to rm command. – Shiping Mar 26 '17 at 14:43
  • 2
    Possible duplicate of [How to avoid "No such file or directory" Error for \`make clean\` Makefile target](http://stackoverflow.com/questions/21949237/how-to-avoid-no-such-file-or-directory-error-for-make-clean-makefile-target) – tripleee Mar 26 '17 at 14:49

1 Answers1

9

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
dbush
  • 205,898
  • 23
  • 218
  • 273