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"
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();
}
};
Next class:
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: undefined reference to `pthread_cancel'
Do this instead:
g++ -pthread -c T.cpp A.cpp Main.cpp
g++ -pthread -o out *.o
-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.
And generally don't use -lpthread anyway. Use -pthread both for compiling and linking.
From the GCC manual:
Adds support for multithreading with the pthreads library. This option sets flags for both the preprocessor and linker.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With