【问题标题】:Why link libraries (like pthread) when they are in the right folder "/lib" and "/usr/lib"?为什么要在正确的文件夹“/lib”和“/usr/lib”中链接库(如 pthread)?
【发布时间】:2011-03-06 07:15:57
【问题描述】:

1.为什么我们需要链接非标准库/包含非标准头文件,而它们已经存在于正确的文件夹中

anirudh@anirudh-Aspire-5920:~/Documents/DUMP$ locate libpthread
/lib/libpthread-2.12.1.so
/lib/libpthread.so.0
/usr/lib/libpthread.a
/usr/lib/libpthread.so
/usr/lib/libpthread_nonshared.a
/usr/lib/xen/libpthread.a
/usr/lib/xen/libpthread_nonshared.a
anirudh@anirudh-Aspire-5920:

ld.so/ld-linux.so - dynamic linker/loader 的手册页说搜索了程序所需的必要库In the default path /lib, and then /usr/lib. 当我的库的 .so 文件已经存在于 /lib 文件夹中时,为什么我需要专门链接它。 -l 选项也用于链接静态库。但是当我对进程执行 pmap 时,我看到正在使用扩展名为 .so 的 pthread 动态库,而不是扩展名为 .a 的动态库。 同样

anirudh@anirudh-Aspire-5920:~/Documents/DUMP$ locate mysql.h
/usr/include/mysql/mysql.h
anirudh@anirudh-Aspire-5920:~/Documents/DUMP$

当它已经存在于文件夹/usr/include 中,这是所有头文件的标准文件夹,那么为什么我需要使用-I 选项专门包含它。

【问题讨论】:

    标签: c linux gcc dynamic-linking static-linking


    【解决方案1】:
    1. 虽然链接器在/lib/usr/lib 中搜索请求的库,但这并不意味着它会自动加载这些库的所有。加载库是一项相当昂贵的操作,因此链接器只加载它知道需要的库。 -l 告诉它需要库。有一些操作系统和工具链会根据头文件中的指令自动尝试找出需要哪些库(Visual C++ 在 Windows 上执行此操作),但这种技术在 Linux 上不使用。
    2. -l 用于静态库和共享库。如果两者都存在,则将使用共享版本,除非将-static 指定给链接器。
    3. 如果您使用#include <mysql/mysql.h>,预处理器将在/usr/include/mysql/mysql.h 中查找它。也就是说,搜索不是递归的 - 如果您指定 <mysql.h> 预处理器将查看 /usr/include/mysql.h不是 /usr/include/mysql/mysql.h

    【讨论】:

    • 感谢您的回答。我最近写了一个使用数学库函数的代码。我在没有链接库的情况下编译它(手册页说我们必须提供 -lm )并且它有效。几天前,它给了我找不到函数“sqrt()”的错误......所以我不得不链接。那么为什么今天没有给出同样的错误呢?
    • @Anirudh,编译器有时会用内联变量替换一些基本的数学函数。是否会发生这种情况取决于许多因素,包括编译标志以及函数的使用方式。如果它没有被内联变体替换,那么 -lm 将成为必要的 - 所以最好只通过 -lm 以防万一。
    • 非常感谢您解决我的问题。你的回答很中肯,很有帮助。
    • 我想您的意思是 预处理器 将在 /usr/include 中查找 ...而不是链接器,它甚至不知道标头是什么。
    猜你喜欢
    • 1970-01-01
    • 2021-10-26
    • 2017-05-12
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    相关资源
    最近更新 更多