对'pthread_mutex_trylock'的未定义引用

enz*_*959 13 c++ pthreads

我有以下测试程序.

#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;
}
Run Code Online (Sandbox Code Playgroud)

如果我在没有添加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 topthread_mutex_trylock中,collect2:ld返回1退出状态

如果我替换指令iret = pthread_mutex_trylock(&mymutex);

iret = pthread_mutex_lock(&mymutex); 如果没有将pthread libarry添加到编译命令,程序编译并运行也没有错误我知道如果我没有使用-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.
Run Code Online (Sandbox Code Playgroud)

有人对pthread_mutex_trylock有关于此无法引用的含义的一些建议吗?

谢谢你的帮助,恩佐

P S*_*ved 16

如果使用pthread函数,则应链接目标文件,-lpthread而不必担心是否包含符号libc.

据说这背后的基本原理是:前一段时间,当使用线程的应用程序在没有线程支持的系统上运行时,会使用libc中的存根.在这样的系统上,pthread_*函数被链接到libc存根,这些存根返回错误,表明没有线程功能.在"线程"系统上,它们链接到pthread库并正常工作.

显然,pthread_mutex_trylock政策改为连接后出现了功能-lpthread.所以没有它的存根.

  • BTW,`-lpthread`不可移植,特别是旧版本的BSD使用`libc_r`,而不是`libpthread`.因此,`-pthread`更便于携带和推荐. (2认同)

Chr*_*ung 14

您应该使用该-pthread选项执行编译和链接,以便于移植.在某些系统上,编译将-D_REENTRANT使用-pthread指定的特定标志添加(例如).

如果您想知道-pthread如何对编译和链接标记执行操作,请运行gcc -dumpspecs.