18

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?

user248075
  • 197
  • 1
  • 1
  • 3

5 Answers5

24

Use:

gcc MyProgram.c -o MyProgram -lpthread 

and dont forget to include the POSIX library in your code. It will compile your code.

muru
  • 197,895
  • 55
  • 485
  • 740
  • 2
    by 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
  • 1
    Also note that in gcc-4.8 there is not -lpthread argument in man 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
1

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.

Mike
  • 105
-1

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

Kushal
  • 2,370
-1

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.

muru
  • 197,895
  • 55
  • 485
  • 740
-1

For C++ program:

g++ -std=c++11 Myprogram.cpp -o MyProgramTest -lpthread
Zanna
  • 70,465