How can I have my makefile compile with the -l flag?
I have a makefile that looks like
myLibrary:
gcc -c myLibrary.c -o myLibrary.o
ar cr lib
Here is a rudimentary, unrealistic makefile that will make the static library libmyLibary
before it makes the program main
, which it will link with the static library
using the -L
(library search-path) and -l
(library) options.
Makefile
.PHONY: all clean
all: libmyLibrary.a main
main: main.o | libmyLibrary.a
$(CC) -o main main.o -L. -lmyLibrary
libmyLibrary.a: myLibrary.o
$(AR) rcs libmyLibrary.a myLibrary.o
clean:
rm -f *.o libmyLibrary.a main
which runs like:
$ make
cc -c -o myLibrary.o myLibrary.c
ar rcs libmyLibrary.a myLibrary.o
cc -c -o main.o main.c
cc -o main main.o -L. -lmyLibrary
As I think you know, it's unrealistic to make both a library and a program
that links with it in the same makefile, since the point of a library is
that you don't need to keep remaking it to link it with many programs. You'd really have
a makefile for libmyLibrary.a
and other makefiles for programs that
use it.
This is how the gcc linkage options -L
and -l
work:
-L/path/to/search
tells the linker to look for any libraries that you specify with the -l
option in /path/to/search
,
before it looks for them in its default search directories. The current directory, .
,
isn't one of the linker's default search directories. So if you want it to
find a library specified with the -l
option in the current directory, then you need to
specify -L.
-lfoo
tells the linker to search for either a dynamic library, libfoo.so
, or a static
library, libfoo.a
, first in your -L
directories, if any, in the order you've
specified them, and then in its default search directories. It stops searching
as soon as if finds either libfoo.so
or libfoo.a
in one of the search directories.
If it finds both of them in the same directory, then by default it will link libfoo.so
with
your program and not link libfoo.a
.
To link purely statically library, use -static, Like
gcc -static main.c libmyLibrary.a
And run executable file ./a.out
GCC Linux.