. Advertisement .
..3..
. Advertisement .
..4..
Hey, guys! I’m back here. I have a trouble with the error: ”undefined reference to pthread create” while I am running this program:
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);
}
Then I get an error:
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 to `pthread_create'
collect2: ld returned 1 exit status
I don’t know where is wrong and how to fix it. Please help me.
The cause:
After looking over your program, I found that while you were compiling a C program with GCC on Linux, and you used the wrong compilation command. You only set up:
-lpthread
is a library specification, not an option. Therefore, the error happened. Solution: You must use pthread flag, so let’s change to this correct command for Linux:When you add pthread to your IDE’s linker libraries, you will no longer get pthread reference errors. Navigate to libraries in Eclipse by using the following sequences: Properties > C/C++ Build > Setting > GCC C++ linker > libraries. Add pthread once you’ve arrived. However, if you can’t find the C/C++ Build option, you can use the CMakeLists.txt file in Eclipse as a solution. Before the add executable command, add the following to the CMakeLists.txt file:
This will allow Eclipse to support CMake pthreads. It will also tell the linker the way to do the same. Another way is using the -pthread argument in add compile options like follows:
If you follow above suggestions, you will eliminate ”Undefined reference to pthread_create” error.