对“pthread_cancel”的未定义引用

2024-03-19

我写了以下内容T与 一起上课pthread。当我使用 g++ -lpthread 编译此类时,它工作正常。但是如果我从另一个类扩展这个类A并一起编译它会返回一个错误; “对 pthread_cancel 的未定义引用”

Code:

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();
    }
}

Main

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

Compile:

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

Error: 对“pthread_cancel”的未定义引用


改为这样做:

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

-lpthread is a linker标志,它仅在链接时使用,而不是编译时使用,因此您拥有的位置不正确 - 链接部分发生在第二步中。

并且一般不使用-lpthread反正。使用-pthread两者都用于编译和链接。

来自海湾合作委员会手册:

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

对“pthread_cancel”的未定义引用 的相关文章

随机推荐