Reputation: 119
I have my .c and .o files in different directory. My make file look like this
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
But when I run it. it somehow manages to compile a file two time.
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
Upvotes: 2
Views: 172
Reputation: 136256
The pattern rules need fixes:
all: $(TARGET)
$(TARGET): $(OBJECTS)
$(CC) -o $@ $^ $(LIB)
$(OBJDIR)/%.o : $(SRCDIR)/%.c | $(OBJDIR)
$(CC) -o $@ -c $(CFLAGS) $<
$(OBJDIR) :
mkdir -p $@
.PHONY : all
You also need automatic dependency generation.
Upvotes: 1
Reputation: 189397
Your $(OBJECTS)
recipe is literally asking it to compile $<
which is the first file in $(SOURCES)
.
Probably simply remove these recipes; make
already knows exactly how to compile C files correctly.
Upvotes: 0