Compile C program with pthread.h header library in Linux.

Hello readers
In this post I will tell you “how to compile a C program with '#include <pthread.h>' header library in GCC or G++ compiler using Linux?".
2-3 min of read this post will help you what is basic and how to do?

Let's begin
C compiler needs to extra argument on compilation time when we use threading in our program.

The solution of this problem is 

Use -lpthread after compile command.
Read this article will give you better understating.

Compile C program with "pthread.h" header in linux.

I am assuming you know about Threading concept in Programming world.
usually we face the problem in Linux with threading in C program, when we use "pthread.h" library in our code. Then simple compile command doesn't able to execute your program. And compiler throw an error(s). see below

Suppose your file name is multithread.c
  • user@ubuntu:~/$ gcc multithread.c
  • thread.c: undefined reference to 'pthread_create'

Then Question is "How to compile our C Program with '#include <pthread.h>' library"?

Solution:: 

When you are using pthread.h library into your C program, you have to add >space<-lpthread just after the compile command "gcc multithread.c" , or "g++ multithread.c -o multithread", this command will tell to compiler, this program have threading active so compile this program with pthread.h library.

Command:
  • user@ubuntu:~/$ gcc multithread.c -lpthread
  • user@ubuntu:~/$ ./a.out

Here:
  • gcc is your compiler.
  • multithread.c is the source file name of your C program.
  • -lpthread is to execute pthread.h libreary file
  • ./a.out is the object file "I think you know better".

Hope you find this article helpful,
😂"Enjoy your code"😁

Thanks for visit

Home 
 

0 comments: