linux - 在 gcc 中放置 `-l' 选项

标签 linux gcc

在使用 gcc 时,我在放置 -l 选项时遇到了一些问题。这是用于重现问题的精简版本。

t.c:

#include <pthread.h>

int main() {
    pthread_create(0, 0, 0, 0);
}

在终端中:

$ gcc -lpthread t.c  
/tmp/ccmkwV7B.o: In function `main':  
t.c:(.text+0x29): undefined reference to `pthread_create'  
collect2: ld returned 1 exit status

$ gcc t.c -lpthread  
$ (compiles ok)

为什么我必须把 -lpthread 放在最后才能让它工作?而且好像这个问题只出现在32位的linux上。

我的环境信息附在下面:
gcc -lpthread t.c 在此机器上失败。

$ gcc --version  
gcc (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1  

$ uname -rm  
3.0.0-12-generic i686

gcc -lpthread t.c 在这台机器上工作。

$ uname -rm  
2.6.18-274.3.1.el5 x86_64  

$ gcc --version  
gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-51)  

我查阅了 gcc 手册,它说“-l 的位置很重要”。具体是什么意思?

最佳答案

来自manual ,

It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. If bar.o refers to functions in z, those functions may not be loaded.

这意味着链接库首先在 gcc 4.1.2 上工作是非常有趣的。这可能与编译器链接到的默认库有关。我知道在某些安装中我不需要显式链接到 pthreads。

进一步思考,我认为问题出在标志 --as-needed 上,它可能在您的 gcc 4.6 系统中默认打开。看这个link进行一些讨论。

关于linux - 在 gcc 中放置 `-l' 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8612147/

相关文章:

c++ - 为什么将语言标准从 -std=gnu++98 提升到 -std=gnu++11

macos - 更改 bjam 使用的 GCC 版本

linux - 断开连接后保持 SSH session 运行 - 过夜

linux - Python RegEx 捕捉数组名称和大小之间的空白

linux - 如何在多宿主客户端上配置 openldap

c - 在 gcc 32 位代码中未定义的对 `_GLOBAL_OFFSET_TABLE_' 的引用,用于一个简单的函数,独立的操作系统

c++ - Intel vs GCC on constexpr

c - D_FORTIFY_SOURCE 和 gcc

java - Ubuntu:从/X11/Xsession.d 中启动的 java 启动 firefox 正在运行但不可见

linux - 按搜索顺序显示目录的 bash 脚本