【问题标题】:Using pthread in c++在 C++ 中使用 pthread
【发布时间】:2011-02-10 09:57:01
【问题描述】:

我在*.cc 文件中使用pthread.h。当我尝试使用pthread_exit(0);pthread_join(mythrds[yy],NULL); 时,它会说:

.cc:(.text+0x3e): undefined reference to `pthread_exit'

当使用 gcc 在 *.c 文件中编译非常相似的代码时,它可以完美运行。如何在 c++ 中使用 pthread ..(我还添加了 -lpthread)

..
void *myThreads ( void *ptr )
{
...
pthread_exit(0); 
}
..

标志:

g++ -lpthread -Wall -static -W -O9 -funroll-all-loops -finline -ffast-math

【问题讨论】:

    标签: c++ linker pthreads linker-errors


    【解决方案1】:

    您可以尝试使用 g++ 的 -pthread 选项。

       -pthread
           Adds support for multithreading with the pthreads library.  This
           option sets flags for both the preprocessor and linker.
    

    【讨论】:

    • 非常感谢,它真的很有帮助。我以为 -lpthread 也有同样的想法,但事实并非如此。
    • 您可以使用 'gcc -dumpspecs' 了解 -pthread 在您的平台上的作用,并查找以 '%{pthread' 开头的内容
    • '-lpthread' 选项仅包括 pthread 库。这可能不足以在您的平台上获得 pthreads 支持。
    【解决方案2】:

    您的 pthread 头文件是否在函数原型周围有 extern "C" { ... }?这是链接器无法在 C++ 中链接的常见情况。

    发生这种情况是因为 C++ 通常会进行名称修饰,以便将参数详细信息编码为符号(允许多态性)。例如函数:

    void x(int);
    void x(void);
    void x(char,int,float,double);
    

    都获得不同的链接器符号。

    如果头文件没有extern "C" { ... },你可能需要自己做:

    extern "C" {
        #include <pthread.h>
    }
    

    希望这会奏效。

    【讨论】:

    • thnk 但问题不在于。
    猜你喜欢
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 2014-11-27
    • 2019-07-12
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    相关资源
    最近更新 更多