make 编译一个文件两次

Make compiling a file two times

我的 .c 和 .o 文件在不同的目录中。 我的 make 文件看起来像这样

CC = cc
SRCDIR = src
OBJDIR = bin
TARGET = main # output binary
# do not edit below this line
SOURCES = $(shell find $(SRCDIR) -type f -name *.c)
OBJECTS = $(patsubst $(SRCDIR)/%,$(OBJDIR)/%,$(SOURCES:.c=.o))
#Flags, Libraries
CFLAGS      := -I. -c 
LIB         := 

all: $(OBJECTS)
    $(CC) $(OBJECTS) -o $(TARGET)

$(OBJECTS):$(SOURCES)
    $(CC) $(CFLAGS) $< $(LIB) -o $@

.PHONY : clean

clean:
    rm bin/*
    rm main

但是当我运行它。它以某种方式设法编译文件两次。

make
cc -I. -c  src/somefile.c  -o bin/somefile.o
cc -I. -c  src/somefile.c  -o bin/main.o
cc bin/somefile.o bin/main.o -o main 
/usr/bin/ld: /usr/lib/gcc/x86_64-redhat-linux/10/../../../../lib64/crt1.o: in function `_start':
(.text+0x24): undefined reference to `main'
collect2: error: ld returned 1 exit status

你的 $(OBJECTS) 配方实际上是要求它编译 $< 这是 $(SOURCES).

中的第一个文件

可能只是删除这些食谱; make 已经知道如何正确编译 C 文件。

模式规则需要修正:

all: $(TARGET)

$(TARGET): $(OBJECTS)
    $(CC) -o $@ $^ $(LIB)

$(OBJDIR)/%.o : $(SRCDIR)/%.c | $(OBJDIR)
    $(CC) -o $@ -c $(CFLAGS) $<

$(OBJDIR) :
    mkdir -p $@

.PHONY : all 

您还需要.