Search code examples
linuxgccstatic-librariesstatic-linking

How to use static library with gcc under linux


I'm trying to use a static library 'mylib.a' created with 'ar'. The examples I have seen use -L and -l to name the library. My attempts at using these fail. However, if I simply put the library file name on the linker command it works. (I'm overlooking something obvious?) Using gcc 4.8.4 Ubuntu 14.04 (see comment in code.) The f?.c and mymain.c are trivially simple. Thanks!

#!/bin/bash

# cc -v    shows...
#  gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.1) 

cc -c -Wall -Wstrict-prototypes -o fa.o fa.c
cc -c -Wall -Wstrict-prototypes -o fb.o fb.c
cc -c -Wall -Wstrict-prototypes -o fc.o fc.c
cc -c -Wall -Wstrict-prototypes -o mymain.o mymain.c

ar -rcs mylib.a  fa.o fb.o fc.o

# THIS WORKS
#cc -o mypgm mymain.o mylib.a

# THESE FAIL WITH ERROR '/usr/bin/ld: cannot find -lmylib'
cc -o mypgm mymain.o -L. -lmylib
# OR 
cc -o mypgm mymain.o -static -L. -lmylib

###

Solution

  • As noted in a comment

    When you use -lname, the linker looks for libname.a or libname.so in one of the directories that it has (already) been told to search for libraries.

    You can either rename your library to libmine.a and then -L. -lmine will work, or rename it to libmylib.a and then -lmylib will work (but the repeated lib looks a bit clumsy, or neophytic).