gcc linker library search order; paths plus static

2020-07-10 10:04发布

Reading through the gcc manual, I believe the following two statements are true:

  1. Library search paths specified on the command line are searched before "default" paths (which I assume means stuff in the LIBRARY_PATH environment variable)

  2. Shared libraries will be linked in preference to static libraries (in the absence of flags saying to do otherwise)

But which of these two dominates? For example, if I type

gcc myprog.cpp -o myprog -Lmypath -lmylibrary

and in mypath there is the static library "libmylibrary.a", and in some place specified in LIBRARY_PATH there is a shared library "libmylibrary.so", which of these libraries will get used? My guess would be that the static library will get used (i.e. (1) dominates) but I am seeing some funny compile errors that make me question this guess, so I wanted to make sure...

1条回答
We Are One
2楼-- · 2020-07-10 11:00

In your example, the static library libmylibrary.a will be linked in preference to any libmylibrary.a or libmylibrary.so that might exist in one of the linker's default search directories. The linker searchs in mypath before any of the default places, and as soon as it finds a libmylibrary.a or libmylibrary.so, it looks no further to satisfy -lmylibrary.

If mypath contained both libmylibrary.a and libmylibrary.so, the latter would be preferred.

I am not sure what source you are referring to by "the gcc manual", but "the gcc linker" is the GNU linker, ld, and you will find the meanings of the commandline options very well explained in its manual

查看更多
登录 后发表回答