我有以下测试程序。
#include <iostream>
#include <cstdlib>
using namespace std;
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, char *argv[])
{
int iret;
iret = pthread_mutex_trylock( & mymutex );
cout << "Test2 !!! " << endl;
pthread_mutex_unlock( & mymutex );
return EXIT_SUCCESS;
}
如果我在没有添加pthread库的情况下编译它,我会得到pthread_mutex_trylock的未解决错误错误,但仅针对函数pthread_mutex_trylock。
如果我用pthread_mutex_trylock替换pthread_mutex_trylock,程序就会被编译并运行得很好而且没有-lpthread *选项。
如果我将-lpthraed选项添加到编译命令中,则运行良好 运行良好: $ g ++ test2.c -o test2 -lpthread 这个警告尚未解决: $ g ++ test2.c -o test2
错误输出示例:
$ g ++ test2.c -o test2
/tmp/ccU1bBdU.o:在函数main':
test2.c:(.text+0x11): undefined reference to
pthread_mutex_trylock'中
collect2:ld返回1退出状态
如果我更换指令 iret = pthread_mutex_trylock(&amp; mymutex);
使用 iret = pthread_mutex_lock(&amp; mymutex); 如果没有将pthread libarry添加到compile命令,程序将编译并运行而不会出现错误 我知道如果我没有使用-lpthread选项,那么有未解决的错误是正确的,但为什么我的其他pthread_函数也没有相同的未解决错误?
我在Fedora 12上使用gcc 4.4.2
$ g++ --version
g++ (GCC) 4.4.2 20091222 (Red Hat 4.4.2-20)
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
对于pthread_mutex_trylock,有人对这个无法引用的含义有一些建议吗?
感谢你的帮助,恩佐
答案 0 :(得分:16)
如果您使用pthread功能,则应将目标文件与-lpthread
相关联,而不必担心libc
中是否包含符号。
这背后的基本原理是said:前一段时间,当使用线程的应用程序在没有线程支持的系统上运行时,会使用libc中的存根。在这样的系统上,pthread_*
函数链接到libc
存根,返回错误,表明没有线程功能。在“线程”系统上,它们与pthread
库链接并正常工作。
显然,在政策更改为与pthread_mutex_trylock
关联后,-lpthread
功能出现了。所以没有它的存根。
答案 1 :(得分:14)
您应该使用-pthread
选项执行编译和链接,以便于移植。在某些系统上,编译将添加特定标记(例如,-D_REENTRANT
)并指定-pthread
。
如果您想知道-pthread
将对您的编译和链接标记做什么,请运行gcc -dumpspecs
。