繁体   English   中英

对'pthread_cancel'的未定义引用

[英]undefined reference to `pthread_cancel'

我用pthread编写了以下T类。 当我使用g ++ -lpthread编译这个类时,它工作正常。 但是如果我从另一个类A扩展这个类并一起编译它会返回一个错误; “对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'的引用

改为:

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

-lpthread是一个链接器标志,它仅在链接时使用,而不是在编译时使用,所以你所拥有它的地方不正确 - 链接部分在第二步中发生。

并且通常不要使用-lpthread 使用-pthread进行编译和链接。

从GCC手册:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM