In this tutorial, we will discuss some of the main causes of this error and how to resolve it.”
Let’s get started.
Cause
There are several reasons why the “Undefined reference to pthread_create” error occurs.
One example code is as shown below:
void *thread(void *vargp);
int main()
{
pthread_t tid;
printf("Hello World fron the main thread!\n");
pthread_create(&tid, NULL, thread, NULL);
pthread_join(tid, NULL);
pthread_exit((void *)NULL);
}
void *thread(void *vargp)
{
printf("I am from main thread!\n");
pthread_exit((void *)NULL);
}
The above code holds a simple pthread program that simply prints a simple text message. However, if we attempt to compile the code above, it returns an error.
Cause 1: Missing Thread Header File
In C, the ability to create multiple threads in a program is provided by the pthread.h. Therefore, before we can use the pthread_create and all its provided functions, we need to include this header file in our program.
Hence, in some cases, failing to include the pthread.h header file will result in the undefied reference.
We can fix this by including the file as shown:
Once included, we can proceed to compile and test our program.
Cause 2: Incorrect Compiler Flag
Another common cause of the “undefined reference to pthread_create” error is compiling your program with the incorrect compiler flags.
For example, if you are compiling your C program with the command:
You will get the “undefined reference to pthreads” error.
While making sure that the pthreads.h file is included in your header file; you need to compile your code with the right compiler flag.
The correct command for the gcc compiler is shown below:
Feel free to replace the output and input filenames.
Adding the -pthread option to the compiler commands allows the compiler to execute the code with the pthread.h library.
Cause 3: Cmake Flag Missing
If you are using a make file to compile your program, you will need to include the pthread options in the file.
You can do so by adding the following line to your make file.
Or
Closing
In this short tutorial, we covered the “Undefined reference to the pthread_create” error when working with POSIX threads. Although we covered the universal causes of this error, you may need to check your development environment and ensure that the required libraries are linked properly.
We hope you enjoyed the tutorial, thanks for reading.