Makefile Linking with shared library fails
c, c++, makefile
Solution
The traditional behaviour of linkers is to search for external functions from left to right in the libraries specified on the command line. This means that a library containing the definition of a function should appear after any source files or object files which use it.
Problem
I was trying to write a shared library and trying to link it to form the final executable. Makefile ``` mystring.out:main.c libmystring.so gcc -I. -L/home/pradheep/myexploration/mystring/ -lmystring main.c -o mystring.out libmystring.so:mystring.o gcc -shared -Wl,-soname,libmystring.so -o libmystring.so mystring.o libmystring.a:mystring.o ar -r libmystring.a mystring.o mystring.o:mystring.h mystring.c gcc -Wall -g -c -fPIC -I. mystring.c clean: rm *.o rm *.a rm *.so rm *.out ``` Here is the Error message: ``` gcc -I. -L/home/pradheep/myexploration/mystring/ -lmystring main.c -o mystring.out /tmp/ccS9UDPS.o: In function `main': main.c:(.text+0x2d): undefined reference to `mystrcpy' main.c:(.text+0x5a): undefined reference to `mystrncpy' main.c:(.text+0x87): undefined reference to `mystrncpy' main.c:(.text+0xa4): undefined reference to `mystrlen' collect2: ld returned 1 exit status make: *** [mystring.out] Error 1 ``` I have already exported the `LD_LIBRARY_PATH` ``` echo $LD_LIBRARY_PATH /home/pradheep/myexploration/mystring ``` Output of my libmystring.so ``` 000004ca T mystrncpy 0000045c T mystrcpy ``` What am i missing ? Solution: The problem was the order of the library -l usage. It should be used after the source file and the correct order as pointed out by Dayal rai is gcc -I. -L/home/pradheep/myexploration/mystring/ main.c -lmystring -o mystring.out and hurray it works.