Home > Software engineering >  MakeFile compiling all the files even if those were already compiled and weren't touched after
MakeFile compiling all the files even if those were already compiled and weren't touched after

Time:04-04

This is my makefile

CFLAGS=-Wall -g -lm

SHELL=/bin/bash

CFILES=$(wildcard *.c)
OBJECTS=$(patsubst %.c,%,$(CFILES))

.PHONY: clean status all

all: $(OBJECTS)

#%:%.c
#   gcc $(CFLAGS) -o $@ $^

$(OBJECTS): $(CFILES)
    @echo "Running : $@ -> $^"
#   gcc $(CFLAGS) -o $@ $(patsubst %,%.c,$@) 

clean:
    rm -f $(OBJECTS)

status:
    @git status
    @git diff --stat

push: clean
    git push

when i am using %:%.c(rule commented in Makefile) it is running fine. By all of this i can only think is that rule $(OBJECTS): $(CFILES) is somehow thinks that any target in OBJECTS depends on all of the values in $(CFILES).

So whenever it is building any single binray, it sees that it depends on all CFILES so it recompile any c file if anyone of those is modified.

So i want to know is there a better way to write the rule $(OBJECTS): $(CFILES), if that is causing the issue. Otherwise If this rule isn't the culprit than what is causing this. I know i can use %:%.c but i think it can cause some problems, as this rule will also holds true for something.h.

I am new with Makefiles, So it would be helpful if you elaborate the cause also, So in future i can prevent that

CodePudding user response:

Your suspicion is correct. When you write:

foo bar biz : foo.c bar.c biz.c
        # do something

(which is what make sees after it expands the variables), make interprets that as:

foo : foo.c bar.c biz.c
        # do something
bar : foo.c bar.c biz.c
        # do something
biz : foo.c bar.c biz.c
        # do something

Your question is a little confusing because you're using the term "objects", which usually means object files (foo.o), instead of binaries or executables.

Anyway, you can do what you want safely with static pattern rules:

$(OBJECTS): % : %.c
        @echo "Running : $< -> $@"
#       gcc $(CFLAGS) -o $@ $<
  • Related