Reputation: 51
I am trying to compile source codes into binary.
Of the two source files, the main function is defined in one(main.c). However I still get the following error while compiling my sources into a binary.
Here is my Makefile:
CC = gcc
LD = ld
AR = ar
NM = nm
OBJCOPY = objcopy
OBJDUMP = objdump
READELF = readelf
CFLAGS += -Wall -I.
LDADD += -lpthread -ldl -L. -llob
BINARY=test
.PHONY: all
all: $(BINARY)
main.o: main.c
$(CC) $(CFLAGS) -c -o $@ $<
sub.o: sub.c
$(CC) $(CFLAGS) -c -o $@ $<
$(BINARY): sub.o main.o
$(CC) $(CFLAGS) $(LDADD) -o $@ $<
.PHONY: clean
clean:
rm -f $(OBJS) $(BINARY)
this returns error:
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In function _start':
(.text+0x20): undefined reference to
main'
collect2: error: ld returned 1 exit status
Please advise!
Upvotes: 1
Views: 627
Reputation: 38315
The error stems from this part
$(BINARY): sub.o main.o
$(CC) $(CFLAGS) $(LDADD) -o $@ $<
The variable $<
refers only to the first dependency, which is sub.o
here. main.o
is hence not linked. The fix is to modify the compile command to
$(CC) $(CFLAGS) $(LDADD) -o $@ $^
where $^
refers to all prerequesites (thanks to @MadScientist for pointing that out). You might also consider storing source and object files in a variable. I'd suggest replacing your rules for compiling sources and linking by the following
SRC = $(wildcard *.c)
OBJ = $(SRC:%.c=%.o)
%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $<
$(BINARY): $(OBJ)
$(CC) $(CFLAGS) $(LDADD) -o $@ $(OBJ)
Here, all .c files in the current directories are compiled into object files and then linked into the executable (adjust the wildcard
line if you don't want every .c file but rather a certain selection).
Upvotes: 1