Makefile compiles the same sources several times

** Modified Question **

Here is a typical template Makefile:

TARGET   = my_prog               # project name

CC       = gcc -o
CFLAGS   = -Wall
SOURCES  := $(wildcard *.c)
INCLUDES := $(wildcard *.h)
OBJECTS  := $(SOURCES:.c=*.o)
rm       = rm -f

$(TARGET): $(OBJECTS)
    @$(CC) $(TARGET) $(CFLAGS) $(SOURCES)
    @echo "Compilation complete!"

clean:
    @$(rm) $(TARGET) $(OBJECTS)
    @echo "Cleanup complete!"

Question: why is line 11 ( @S(CC) $(TARGET) ...) still echoing when called make?

Answer. Because the problem is in the default rule and line 11 is fine.

** UPDATE **

Now i have it Makefile

# project name
TARGET   = my_prog

CC       = gcc -c
CFLAGS   = -Wall -I.
LINKER   = gcc -o
LFLAGS   = -Wall
SOURCES  := $(wildcard *.c)
INCLUDES := $(wildcard *.h)
OBJECTS  := $(SOURCES:.c=*.o)
rm       = rm -f

$(TARGET): $(OBJECTS)
    $(LINKER) $(TARGET) $(LFLAGS) $(OBJECTS)

$(OBJECTS): $(SOURCES) $(INCLUDES)
    $(CC) $(CFLAGS) $(SOURCES)

clean:
    $(rm) $(TARGET) $(OBJECTS)

Question: Why $(CC) $(CFLAGS) $(SOURCES)is it executed n times, where n is the number of source files?

** UPDATE 2 **

Would this be a good way to solve this problem (seems to work ...)?

$(TARGET): obj
    $(LINKER) $(TARGET) $(LFLAGS) $(OBJECTS)

obj: $(SOURCES) $(INCLUDES)
    $(CC) $(CFLAGS) $(SOURCES)
+3
source share
2 answers

$(CC) $(CFLAGS) $(SOURCES) n , n , n , , $(TARGET) . , , PHONY, .

. , , . , Make , , Make , :

$(OBJECTS): %.o : %.c $(INCLUDES)
  $(CC) $(CFLAGS) $<

- , , . , , .

EDIT:

" 2" - ,

.PHONY: obj

, "obj". Make obj , .

, , . foo.c, Make .

$< . " ". , Make foo.o, foo.c.

EDIT:

( !) , , PHONY: obj , TARGET, - . , " 2" , .

+5

, .o, geverating my_prog

, .o, make .

:

@echo "starting compilation"

11

, " " gcc.

, 10 :

$(TARGET): $(SOURCES)

?

+1

Source: https://habr.com/ru/post/1773350/


All Articles