Fabio
Fabio

Reputation: 3067

Makefile : fclean gives error if program is not yet built

I have 2 makefiles that crash when I use the command make re if the program (or library) is not yet previously built, because make re calls fclean, which should remove the file and crashes if the file is not found. Here is one of the makefiles for a library

NAME = lib.a

CC = cc
CFLAGS = -Wall -Wextra -Werror
SRC = *.c

OBJ = $(SRC:.c=.o)

INC = Includes

all: $(NAME)

$(NAME):
    @$(CC) -I $(INC) $(CFLAGS) -c $? $(SRC)
    @ar rc $(NAME) $? $(OBJ)
    @ranlib $(NAME)

clean:
    @/bin/rm -f $(OBJ)

fclean: clean
    @/bin/rm $(NAME)

re: fclean all

.PHONY: all clean fclean re

when I call make re and lib.a still doesnt exist I get

rm: lib.a: No such file or directory
make: *** [fclean] Error 1

Is there anyway to get it to just ignore the fclean command if lib.a is not found?

thanks

Upvotes: 1

Views: 2995

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80931

See the Errors in Recipes section of the GNU make manual for how to deal with this at the make level.

In this instance, however, you can also deal with this at the rm level. The -f flag to rm will cause it ignore non-existent files (as well as not prompting for deletion and in basically all other ways not stopping or returning a failure... ever).

That being said it shouldn't, in general, ever be necessary to clean before a new build. That generally seems necessary when a makefile is incorrectly written (as yours is) to not properly teach make what the dependencies between sources and targets are (and/or by not using targets essentially at all and always just building from scratch as you are).

Upvotes: 1

Related Questions