【问题标题】:with -lpthread, g++ compiler error, "undefined reference to " semaphore calls such as `sem_open'带有 -lpthread,g++ 编译器错误,“未定义的引用”信号量调用,例如 `sem_open'
【发布时间】:2012-06-22 02:26:32
【问题描述】:

我是 posix 线程库的新手,我尝试使用以下教程编译示例代码:

g++ -lpthread agreement.cpp -o agreement

但是我无法编译代码并收到以下错误消息:

a3q2.cpp:(.text+0x7e): undefined reference to `sem_open'
a3q2.cpp:(.text+0xab): undefined reference to `sem_wait'
a3q2.cpp:(.text+0x290): undefined reference to `sem_post'
a3q2.cpp:(.text+0x2af): undefined reference to `sem_close'
a3q2.cpp:(.text+0x2bb): undefined reference to `sem_unlink'
collect2: ld returned 1 exit status
make: *** [a3q2_exe] Error 1

我知道编译需要 -lpthread 才能工作,但是我可能需要其他选项来解决问题吗?如果不是,我该如何安装“正确”的 pthread 库?

感谢您的帮助!

【问题讨论】:

  • 你想要-pthread,而不是-lpthread。使用 pthreads 支持进行编译可能需要的不仅仅是一个库。您的平台可能需要-lrt 信号量(您查看手册页了吗?)。
  • 未定义的引用是链接器,而不是编译器错误。
  • 此外,提供符号的对象(和档案)必须在链接时使用这些符号对象之后排序。在这里可能无关紧要,但要养成将-lfoo 放在命令的end 而非start 的习惯。

标签: c++ linux multithreading system-calls undefined-reference


【解决方案1】:

你想要编译选项-pthread(如果你真的在使用pthreads)。如果您只需要它们在librt 中的那些功能,请使用-lrt

【讨论】:

  • 非常感谢,我能够用-pthread 解决问题,但您能详细说明为什么会这样吗? -lpthread-pthread 有什么区别?谢谢
  • @Mike:如果您查看 gcc 的手册页,-pthread:“使用 pthreads 库添加对多线程的支持。此选项为预处理器和链接器设置标志。”确切的标志可能因平台而异;在您的系统上,它可能类似于“-D__PTHREADS -lpthread -lrt”,这意味着仅传递“-lpthread”是不够的。您可以准确地弄清楚它在您关心的每个平台上映射到什么,然后通过它传递,为什么?
  • @Mike:除此之外,“gcc 兼容模式”中的一些其他编译器(我相信 icc)也可能使用 -pthread 来影响一些代码生成和/或优化决策,所以如果你结束- 绕着它跑,你最终可能会得到编译和链接但百万分之一崩溃的代码……
猜你喜欢
  • 2016-12-09
  • 2011-06-22
  • 2018-11-29
  • 2014-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
相关资源
最近更新 更多