shantanu
shantanu

Reputation: 2418

undefined reference to `pthread_cancel'

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'

Upvotes: 3

Views: 7200

Answers (1)

Mat
Mat

Reputation: 206727

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.

Upvotes: 12

Related Questions