在gcc中放置`-l'选项 [英] Placement of `-l' option in gcc
问题描述
当使用 gcc
时,对于 -l </ code>选项的位置有一些问题。这是一个精简版,用于重现问题。
tc:
#include< pthread.h>
int main(){
pthread_create(0,0,0,0);
}
以及在终端中:
$ gcc -lpthread tc
/tmp/ccmkwV7B.o:函数`main':
tc :(。text + 0x29):undefined reference to `pthread_create'
collect2:ld返回1退出状态
$ gcc tc -lpthread
$(编译成功)
为什么我必须最后放置 -lpthread
才能使它工作?而且似乎这个问题只发生在32位的linux上。
我的环境信息如下所示:
gcc -lpthread tc
在本机上失败。
$ gcc --version
gcc(Ubuntu / Linaro 4.6.1-9ubuntu3)4.6.1
$ uname -rm
3.0.0-12-generic i686
gcc -lpthread tc
可以在这台机器上运行。
$ 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 ,
你写这个选项;链接器按照它们指定的顺序搜索和处理库和对象文件。因此,在文件
foo.o之后,
搜索库foo.o -lz bar.o z
但在bar.o
之前。如果bar.o
引用z
中的函数,则可能不会加载这些函数。
这意味着链接库首先在gcc 4.1.2上工作是非常有趣的。这可能与编译器链接的默认库有关。我知道在一些安装中,我不需要明确链接到pthread。
经过进一步的反思,我认为问题出现在标记 - 根据需要
,可能是默认在你的gcc 4.6系统中。有关讨论,请参阅此链接。
I have some trouble with the placement of the -l
option when using gcc
. Here's a stripped down version for reproduce the problem.
t.c:
#include <pthread.h>
int main() {
pthread_create(0, 0, 0, 0);
}
and in terminal:
$ 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)
Why do I have to put -lpthread
in the end to make it work? And it seems that this problem only occurs on 32bit linux.
My environment info is attached below:
gcc -lpthread t.c
fails on this machine.
$ gcc --version
gcc (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
$ uname -rm
3.0.0-12-generic i686
gcc -lpthread t.c
works on this machine.
$ 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)
I looked up the gcc manual, and it says that "the placement of -l is significant". What exactly does it mean?
From the 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.
This means it is very interesting that linking the library first works on gcc 4.1.2. This might have to do with the default libraries linked to by the compiler. I know on some installations I don't need to explicitly link to pthreads.
On further reflection, I think the issue is with the flag --as-needed
, which may be on by default in your gcc 4.6 system. See this link for some discussion.
这篇关于在gcc中放置`-l'选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!