Reputation: 323
I am trying to link to a shared library. But I kept getting the undefined reference error. The following is makefile:
LIBDIR :=./lib
LIB :=-lminus
OBJDIR :=objdir
SOURCES=$(wildcard ./src/*.c)
OBJS :=$(patsubst ./src/%.c, $(OBJDIR)/%.o, $(SOURCES))
INCPATH = -Ilib -Isrc
vpath %.h ./src ./lib
vpath %.c ./src ./lib
optest : $(OBJS)
cc -o optest $(OBJS)
$(OBJDIR)/main.o : main.c add.h mul.h did.h minus.h
cc $(INCPATH) -o $@ -c $< -L$(LIBDIR) $(LIB)
$(OBJDIR)/%.o: %.c %.h | $(OBJDIR)
cc -o $@ -c $<
$(OBJDIR):
mkdir $@
clean :
rm -rf $(OBJDIR)
rm -f optest
rm -f ./src/*.o
The shared library is called libminus
, which is put in the ./lib
directory. The main
function in main.c
uses the function minus
defined in this library. I searched online, people met this problem before. Most of their problems were solved after the shared libraries were put after the object files in the rule command. I also tried this, but it didn't work for me. The error I got is as follows:
mkdir objdir
cc -o objdir/mul.o -c ./src/mul.c
cc -o objdir/did.o -c ./src/did.c
cc -Ilib -Isrc -o objdir/main.o -c ./src/main.c -L./lib -lminus
cc -o objdir/add.o -c ./src/add.c
cc -o optest objdir/mul.o objdir/did.o objdir/main.o objdir/add.o
objdir/main.o: In function `main':
main.c:(.text+0xa5): undefined reference to `minus'
collect2: error: ld returned 1 exit status
makefile:11: recipe for target 'optest' failed
make: *** [optest] Error 1
Can any one give some suggestion? Thank you.
Upvotes: 0
Views: 453
Reputation: 58647
You're putting the lib stuff into the wrong rule:
$(OBJDIR)/main.o : main.c add.h mul.h did.h minus.h
cc $(INCPATH) -o $@ -c $< -L$(LIBDIR) $(LIB)
This just compiles main.c
to main.o
. The -L
and $(LIB)
don't belong here. They have to be in the build recipe of this rule, which links the executable:
optest : $(OBJS)
cc -o optest $(OBJS)
Upvotes: 2