Compiling C program with pthread.h library in Linux

The solution is:
Use -lpthread after the compile command.

Please read complete article to learn better.

Compile C program with pthread.h in Linux

Threads/ Processes are the mechanism by which you can run multiple code segments at a time, threads appear to run concurrently; the kernel schedules them asynchronously, interrupting each thread from time to time to give others chance to execute.

We usually face the problem with threading program in C language in Linux. When we use pthread.h library in our program, program doesn't execute using simple (normal) compile command. After including pthread.h header file, program doesn't compile and return error(s).

Let's understand with an example: Here is a program that will demonstrate example of threading.


Program - thread.c

#include <stdio.h>
#include <pthread.h>
  
/*thread function definition*/
void* threadFunction(void* args)
{
    while(1)
    {
        printf("I am threadFunction.\n");
    }
}
int main()
{
    /*creating thread id*/
    pthread_t id;
    int ret;
  
    /*creating thread*/
    ret=pthread_create(&id,NULL,&threadFunction,NULL);
    if(ret==0){
        printf("Thread created successfully.\n");
    }
    else{
        printf("Thread not created.\n");
        return 0; /*return from main*/
    }
  
    while(1)
    {
      printf("I am main function.\n");      
    }
  
    return 0;
}

Now compile program as normally (as usual we compile any c program)

The compile command is:
gcc thread.c -o thread
program will throw an error, and the error is:
    sh-4.3$ gcc thread.c -o thread
    thread.c: undefined reference to 'pthread_create'

Then, how to compile C program with pthread.h library?

To compile C program with pthread.h library, you have to put -lpthread just after the compile command gcc thread.c -o thread, this command will tell to the compiler to execute program with pthread.h library.

The command is:
gcc thread.c -o thread -lpthread

  • gcc is the compiler command.
  • thread.c is the name of c program source file.
  • -o is option to make object file.
  • thread is the name of object file.
  • -lpthread is option to execute pthread.h library file.

See the output after running this command

    sh-4.3$ gcc thread.c -o thread -lpthread
    sh-4.3$ ./thread
    
    Thread created successfully.
    I am threadFunction.
    I am threadFunction.
    I am threadFunction.
    I am threadFunction.
    …
    …
    I am threadFunction.
    I am main function.
    I am main function.
    I am main function.
    I am main function.
    …
    …
    I am main function.
    I am threadFunction.

    … and so on.




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.