SleepyCat
SleepyCat

Reputation: 37

Makefile link static library

just a simply makefile here, but always ld: linking error on static library linking
the folder tree

├── include
│   └──main.h
├── lib
│   └── libmyrand.a
├── main.c
├── main.o
└──  Makefile

  1 TARGET= main
  2 
  3 INC = -Iinclude
  4 
  5 LIBDIR = ./lib
  6 LIB = libmyrand
  7 
  8 OBJS = main.o
  9 
 10 SOURCES = main.c
 11 
 12 
 13 all: $(TARGET)
 14 
 15 $(TARGET): $(OBJS)
 16   gcc -o main  $< -L$(LIBDIR) -l$(LIB)
 17 
 18 $(OBJS):  $(SOURCES)
 19   gcc -c -g $(INC)  $< 
 20 
 21 .PHONY: clean
 22 
 23 clean:
 24   rm -f *.o

make error message:

gcc -c -g -Iinclude  main.c 
gcc -o main -L./lib -llibmyrand main.o 
/usr/bin/ld: cannot find -lmyrand
collect2: error: ld returned 1 exit status
make: *** [Makefile:16: main] Error 1

if i change the line #15-#16 to

 15$(TARGET): $(OBJS)
 16   gcc -o main  $< ./lib/libmyrand.a

make done! balabala

Upvotes: 0

Views: 571

Answers (1)

MadScientist
MadScientist

Reputation: 100781

This is not a makefile problem. This is a misunderstanding of how the compiler and linker work. If you typed the original command at your shell prompt, not via make, then it would fail the same way. So, you know it doesn't have anything to do with make.

The compiler command line -lfoo option will always look for libraries name libfoo.so or libfoo.a. So if you want to use -lmyrand, then you need to name your library libmyrand.so or libmyrand.a.

.a is static libraries and .so is shared libraries, of course, so if you are using static libraries you want libmyrand.a.

Upvotes: 1

Related Questions