C++ 带-lpthread,g++;编译器错误,";未定义的引用;信号量调用,如'sem#u open';

C++ 带-lpthread,g++;编译器错误,";未定义的引用;信号量调用,如'sem#u open';,c++,linux,multithreading,system-calls,undefined-reference,C++,Linux,Multithreading,System Calls,Undefined Reference,我是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 refe

我是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
(如果您确实在使用pthreads)。如果您只需要这些函数,它们位于
librt
中,那么请使用
-lrt

您想要的
-pthread
,而不是
-lphread
。使用pthreads支持编译可能需要的不仅仅是库。您的平台可能要求信号量使用
-lrt
(是否检查手册页?)。未定义的引用是链接器,而不是编译器错误。此外,提供符号的对象(和存档)必须在链接时在使用这些符号的对象之后排序。这在这里可能不重要,但是习惯于在命令末尾而不是开始处放置
-lfoo
。非常感谢,我能够使用
-pthread
解决问题,但是您能详细说明原因吗?那么
-lpthread
-pthread
之间有什么区别呢?Thanks@Mike:如果查看gcc的手册页,-pthread:“使用pthreads库添加对多线程的支持。此选项为预处理器和链接器设置标志。”确切的标志可能因平台而异;在您的系统上,它可能类似于“-D_upthreads-lpthread-lrt”,这意味着仅仅传递“-lpthread”是不够的。你可以准确地找出它在你所关心的每个平台上映射到什么,并通过为什么来传递它?@Mike:除此之外,其他一些处于“gcc兼容模式”的编译器(我相信icc)也可能使用-pthread来影响一些代码生成和/或优化决策,所以如果你最终绕过它,您可能最终得到编译和链接的代码,但崩溃次数为百万分之一…