The undefined reference appears in Linux pthread_create. Is there anyone who can help me?

Asked 1 years ago, Updated 1 years ago, 107 views

I'm following https://computing.llnl.gov/tutorials/pthreads/ I keep getting errors when I run the code below.

Even though pthread.h was included, it keeps saying pthread_create is not defined Why is this happening? My computer is Ubuntu Linux 9.04.

corey@ubuntu:~/demo$ gcc -o term term.c term.c: In function ‘main’: term.c:23: warning: incompatible implicit declaration of built-in function ‘exit’ /tmp/cc8BMzwx.o: In function main': term.c:(.text+0x82): undefined reference topthread_create' collect2: ld returned 1 exit status

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS     5

void *PrintHello(void *threadid)
{
   long tid;
   tid = (long)threadid;
   printf("Hello World! It's me, thread #%ld!\n", tid);
   pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   for(t=0; t<NUM_THREADS; t++){
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

linux c multithreading pthreads

2022-09-22 22:20

2 Answers

at the terminal gcc -pthread -o term term.c Compile to .


2022-09-22 22:20

gcc term.c -lpthread

Additionally, #include <stdlib.h> is missing.


2022-09-22 22:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.