在使用 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 libraryz
after filefoo.o
but beforebar.o
. Ifbar.o
refers to functions inz
, 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/