gpt4 book ai didi

c++ - 对 `pthread_cancel' 的 undefined reference

转载 作者:太空狗 更新时间:2023-10-29 23:36:00 39 4
gpt4 key购买 nike

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

代码:

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”的 undefined reference

最佳答案

改为这样做:

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

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

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

来自 GCC 手册:

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

关于c++ - 对 `pthread_cancel' 的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23870233/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com