undefined reference to `pthread_cancel'

淺唱寂寞╮ 提交于 2021-01-28 03:22:03

问题


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'


回答1:


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.



来源:https://stackoverflow.com/questions/23870233/undefined-reference-to-pthread-cancel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!