How to know if a library exists or is up to date with makefile

Viewed 1433

Here is my Makefile:

NAME = fillit

FLAGS = -Wall -Wextra -Werror

LIB_NAME = libft.a

LIB_DIR = ../libft/

LIB_PATH = $(LIB_DIR)$(LIB_NAME)

OBJ_DIR_NAME = objects

OBJ_DIR = $(OBJ_DIR_NAME)/

HEADER_DIR = ../libft

SRC = main.c

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

all :
    mkdir -p $(OBJ_DIR_NAME)
    $(MAKE) $(NAME)

$(NAME) : $(OBJ) $(LIB_PATH) 
    gcc -o $(NAME) $(addprefix $(OBJ_DIR), $(OBJ)) -L$(LIB_DIR) -lft 

$(LIB_PATH) : $(LIB_PATH) 
    $(MAKE) -C $(LIB_DIR) --no-print-directory

%.o : %.c 
    gcc $(FLAGS) -I$(HEADER_DIR) -c $<
    mv $@ $(OBJ_DIR)

clean : 
    rm -f $(addprefix $(OBJ_DIR), $(OBJ))
    rm -rvf $(OBJ_DIR_NAME)

fclean : clean
    rm -f $(NAME)
    rm -f $(addprefix $(LIB_DIR), $(LIB_NAME))

re: fclean
    make

When i write $(LIB_PATH) : $(LIB_PATH) i'm expecting that my Makefile check if my lib is updated or exist and if that's not the case compile it (like objects and sources) but when i do make it only argue about circular rules and compile anyway my library.

Then, what should i write for when i do make, it enter in the $(LIB_PATH): only when my library hasn't been compiled yet?

1 Answers

This is a common problem with hierarchical Makefiles. You don't want to have to specify the library dependencies twice (i.e., once to know when to launch the sub-makefile, and again in the sub-makefile to actually build the target) so you just have to call the sub-makefile each time to let it determine if it needs to rebuild.

Try:

.PHONY: $(LIB_PATH) 
$(LIB_PATH): 
[tab] $(MAKE) -C $(LIB_PATH) --no-print-directory

This should cause make to run in the $(LIB_PATH) directory every time this makefile evaluates a target that depends on $(LIB_PATH).

.PHONY is meant for targets that don't really represent files, like clean. It just marks the target as 'stale' even if a file happens to exist with that name and is fresh.

Related