Linking static library with -l flag

二次信任 提交于 2020-11-28 03:07:21

问题


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 libmyLibrary.a myLibrary.o

and then I compile my main program with

main:
    gcc -g -c -o main.o main.c
    gcc main.o -o main libmyLibrary.a

The above makefile works, but if I want to replace

libmyLibrary.a

with -lmyLibrary I get an error. Shouldn't both be working the same?


回答1:


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.




回答2:


To link purely statically library, use -static, Like

gcc -static main.c libmyLibrary.a

And run executable file ./a.out GCC Linux.



来源:https://stackoverflow.com/questions/42257463/linking-static-library-with-l-flag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!