I'm a beginner and I'm new to Ubuntu. I just installed it and want to run a C program. I have no idea what platform to use or where to write the code. I need to use the pthread.h header file in the program. Can anyone help me?
-
possible duplicate of How to compile c & c++ programs? – Elder Geek Feb 19 '15 at 15:22
5 Answers
Use:
gcc MyProgram.c -o MyProgram -lpthread
and dont forget to include the POSIX library in your code. It will compile your code.

- 197,895
- 55
- 485
- 740

- 399
-
2by default GCC does not include the pthread library. so you have to include the library using lpthread argument. – Parthiv Shah Apr 05 '14 at 09:30
-
1Also note that in gcc-4.8 there is not
-lpthread
argument inman gcc
. But there is a-pthread
argument. Both work fine on Ubuntu 14.04 with gcc-4.8. – Elijah Lynn Aug 19 '16 at 00:07 -
this is so wrong answer. you need
-pthread
both for compilation and linking options – BЈовић Mar 01 '23 at 09:58
If you are going to compile a C program with pthread.h in LINUX using GCC or G++ you will have to use –lpthread option after the compile command.
gcc xyz.c -o xyz -lpthread
Here,
gcc is compiler command (compiler name)
xyz.c is a source file name.
-o is an option to create objcect file.
xyz is the name of object (binary) file.
-lpthread is an option for pthread.h
for more details here is the link conatining complete article on it.
Compiling C program with pthread.h in Linux.

- 105
First thing you'll need in Ubuntu to compile C/C++ programs is installing GCC (Gnu Compiler Collection) which is part of build-essential
package , do that by running:
sudo apt-get install build-essential
Then you can test if you have it installed by running gcc
. If you you see error like Fatal error: file not provided
(not sure exact error message, but should be something similar), that means you have compiler ready.
And for editing your Code, you can use already available Gedit, just search for it in Dash.
Now following is the syntax to compile your C source file, run following where your file is:
gcc MyProgram.c -o MyProgram
Where, switch -o
is optional, but provided to mention name of Binary file which should be created out of your source.
Then simply run ./MyProgram
to run your binary.
Note that pthread.h
as you mentioned (POSIX Thread) should be available by default with GCC, so simply including it in your C file will do that job, in case it's not available, a simple Google search should help. ;)
Update
Too long, didn't read? check this. :D

- 2,370
If it gives error than you can try out same command by interchanging the parameters as like
gcc -lpthread -o output_file program_pthread.c
after that ./output_file
provides output for program and here program_pthread.c
is the pthread program you have implemented.

- 197,895
- 55
- 485
- 740