未定义对"pthread_cancel"的引用 [英] undefined reference to `pthread_cancel'

查看:221
本文介绍了未定义对"pthread_cancel"的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 pthread 编写了以下 T 类.当我使用g ++ -lpthread编译此类时,它工作正常.但是,如果我从另一个类 A 扩展该类并一起编译,则会返回错误;对pthread_cancel的未定义引用"

I have written the following T class with pthread. When i compile this class using g++ -lpthread then it's working fine. But if i extend this class from another class A and compile all together it's returns an error; "undefined reference to pthread_cancel"

代码:

class T{
private:
    pthread_t thread;
public:
    void start(){
        pthread_create(&thread,NULL,&run,this);
    }
    void destroy_thread(){
        pthread_cancel(thread);
    }
    static void* run(void*){}
    ~Thread(){
        destroy_thread();
    }
};

下一堂课

class A:T{
    A(){
      start();
    }
}

主要

int main(){
  A a;
  return 0;
}

编译:

g++ -c T.cpp A.cpp Main.cpp -lpthread 
g++ -o out *.o

错误:对"pthread_cancel"的未定义引用

推荐答案

相反,请执行以下操作:

Do this instead:

g++ -pthread -c T.cpp A.cpp Main.cpp
g++ -pthread -o out *.o

-lpthread 是一个 linker 标志,它仅在链接时使用,而不是在编译时使用,因此在不正确的地方-链接部分发生在第二个链接中步骤.

-lpthread is a linker flag, it's used only when linking, not compiling, so where you have it isn't correct - the linking part happens in the second step.

通常无论如何都不要使用 -lpthread .同时使用 -pthread 进行编译和链接.

And generally don't use -lpthread anyway. Use -pthread both for compiling and linking.

来自GCC手册:

使用pthreads库添加了对多线程的支持.此选项为预处理器和链接器设置标志.

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

这篇关于未定义对"pthread_cancel"的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆