How can I write a Makefile that compile object files from another directory?
17:35 01 Mar 2026

I'm trying to write a Makefile that just compile object files from source file in a separate directory. My full code is

CFLAGS = -g -I/home/daemunozr/programming/libutils/headers
CC = gcc
SOURCE_PATH = /home/daemunozr/programming/libutils/objects
SOURCE_FILE := debug.c safe_alloc.c
OBJECTS_FILES := $(SOURCE_FILE:%.c=%.o)
SOURCE_TARGET := $(addprefix $(SOURCE_PATH)/, $(SOURCE_FILE))

.PHONY : clean all

all : $(OBJECTS_FILES)

%.o: %.c
    $(CC) -c $(CFLAGS) $< -o $@

$(OBJECTS_FILES) : $(SOURCE_TARGET)
    $(CC) -c $(CFLAGS) $< -o $@

clean:
    rm -f *.o

If I delete

%.o: %.c
    $(CC) -c $(CFLAGS) $< -o $@

just compile for one target, but if I delete

$(OBJECTS_FILES) : $(SOURCE_TARGET)
    $(CC) -c $(CFLAGS) $< -o $@

it says that there aren't prerequisite. How can I do this without being redudent?

makefile build gnu-make