gcc - 为什么使用 -l 时 gcc 会动态链接?

标签 gcc linker shared-libraries static-libraries

我使用 pthread 库做了一个“Hello World”程序。
我用这种简单的方式编译它:

$ gcc main.c -lpthread

根据 gcc 文档(“链接选项”部分):

-llibrary [...] The linker searches a standard list of directories for the library, which is actually a file named liblibrary.a. The linker then uses this file as if it had been specified precisely by name. [...]



所以,我的理解是:gcc 正在寻找 libpthread.a 。鉴于 .a 结尾,这应该是一个静态库。

但是,这是动态链接的:
$ ldd a.out
        linux-vdso.so.1 =>  (0x00007fffde3c3000)
        libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fb345820000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fb345456000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fb345a3d000)

我错过了什么?

最佳答案

-l|--library 的文档GCC 手册中的选项具有误导性,
因为它没有指定选项在支持的系统上的行为
共享库,或警告我们它不这样做。-l选项传递给链接器,通常是 GNU ld (或直接替代)。 ld manual 中该选项的文档
是优越的,并明确表明共享库将满足 -l选项
优先于静态库。

-l namespec

--library=namespec

Add the archive or object file specified by namespec to the list of files to link. This option may be used any number of times. If namespec is of the form :filename, ld will search the library path for a file called filename, otherwise it will search > the library path for a file called libnamespec.a.

On systems which support shared libraries, ld may also search for files other than libnamespec.a. Specifically, on ELF and SunOS systems, ld will search a directory for a library called libnamespec.so before searching for one called libnamespec.a. (By convention, a .so extension indicates a shared library.) Note that this behavior does not apply to :filename, which always specifies a file called filename.

The linker will search an archive only once, at the location where it is specified on the command line. If the archive defines a symbol which was undefined in some object which appeared before the archive on the command line, the linker will include the appropriate file(s) from the archive. However, an undefined symbol in an object appearing later on the command line will not cause the linker to search the archive again.

...


(我的重点)

关于gcc - 为什么使用 -l 时 gcc 会动态链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52282576/

相关文章:

c++ - 从共享库加载方法,该方法调用在子类中实现的方法

linux - 在下一个 Debian 小版本中库版本会变得不可用吗?

linux - 如何确保 numpy BLAS 库可用作动态可加载库?

GCC ARM 汇编预处理器宏

c - 错误 : expected delcaration specifiers or '...' before 'time' [C]

gcc - 为什么gcc在/usr/include/x86_64-linux-gnu中搜索在/usr/include之前

c++ - Netbeans 8.1(用于 C/C++)找不到我的编译器(gcc-6.0.0 开发版)

c - 为链接器生成目标文件 (.o)

c - STM32F7-从RAM和闪存执行代码

linux - 关于 GCC 链接器搜索顺序的一些问题