Makefile relinking

299 Views Asked by At

I am doing a school project, my makefile is always relinking and I can't figure out why. I need to compile the objs with a library (libft that will have a libft.a file, so I need to create the library using other makefile). Also what are the best resources to learn makefile?

SRCS = src/pipex.c \
       src/utils.c \

OBJS = $(SRCS:.c=.o)

NAME = pipex
LIBFT       = libft.a
LIBFT_DIR := ./libft
LIBFT_LIB := $(LIBFT_DIR)/$(LIBFT)
CC = cc
FLAGS = -Wall -Wextra -Werror
LIBC = ar rc
RM = rm -f

all: $(NAME)

$(NAME): $(OBJS) $(LIBFT)
    $(CC) $(FLAGS) $(OBJS) $(LIBFT_LIB) -o $(NAME)

debug: $(OBJS) $(LIBFT)
    $(CC) $(FLAGS) -g $(SRCS) $(LIBFT_LIB) -o $(NAME)
    
$(LIBFT):
    @cd $(LIBFT_DIR) && $(MAKE) --silent

clean:
    cd $(LIBFT_DIR) && $(MAKE) clean
    $(RM) $(OBJS) $(BNS_OBJS)

fclean: clean
    cd $(LIBFT_DIR) && $(MAKE) fclean
    $(RM) $(NAME)

re: fclean all

.PHONY: $(LIBFT)

I have tried to change the libft command to silent so no output to the screen and change the OBJS to the SRCS in $(NAME) command.

1

There are 1 best solutions below

1
Beta On

The problem is a confusion of libft.a with ./libft/libft.a.

Look at this rule:

$(LIBFT):
    @cd $(LIBFT_DIR) && $(MAKE) --silent

The target is libft.a, but it doesn't actually build libft.a, it builds ./libft/libft.a. Nothing builds libft.a (in the working directory), but the pipex and debug rules have it as a prerequisite. So every time you tell Make to build one of those targets, Make sees that libft.a does not exist, so it tries to build it and then relink everything.

The fix is simple: give things accurate names:

$(NAME): $(OBJS) $(LIBFT_LIB)
    $(CC) $(FLAGS) $(OBJS) $(LIBFT_LIB) -o $(NAME)

debug: $(OBJS) $(LIBFT_LIB)
    $(CC) $(FLAGS) -g $(SRCS) $(LIBFT_LIB) -o $(NAME)