Search code examples
makefileobject-files

Why is my Makefile rule not deleting .o files?


My Makefile works but I'm still getting the main.o file created when calling make.
I've been looking through Stack Overflow for topics like mine but I haven't been able to understand the reason.

Here's the Makefile's content:

EXEC=program
SOURCES=main.c
OBJECTS=$(SOURCES:.c=.o)
CC=gcc -pthread -lpthread
CFLAGS=-std=gnu99 -g

.PHONY: clean

default: $(EXEC)

main.o: main.c
clean:
    -rm *.o $(objects) program

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

$(EXEC): $(OBJECTS)
    $(CC) -o $@ $^

Solution

  • If you want your object files removed after the build step just append the rm -f *.o command to the $(EXEC) target.

    Also, a few notes pointed out in the comments:

    • Makefile variable names are case-sensitive. Use either objects or OBJECTS, not both.

    • Instead of hard-coding program in your clean target, you should instead use $(EXEC). That way you won't have to change it every time you change your program's name.

    • You usually want .o files to be left after compiling so you don't have to recompile everything after a small change.