Compile and run C Program in Linux or Unix | Compiling C program using GCC

Spread the love

Compiling-and-running-c-program-in-ubuntu-linux-systems

Compiling C program on Linux ( Ubuntu, CentOS, Fedora )

Here are the steps for Compiling C program under GNU Linux system.

  • Create a source file.
  • Compile the source file.
  • Run the Executable file.

Create a Source File:

First of all create a source file by using your favourite editor. I am using  vim editor and let’s write a simple hello world program.

 
Save the above file and exit out of editor. ( Use :wq if you are using vim editor)
 
Now have created the program. Lets go ahead with the next step. Compilation.

Compiling C Program:

All Linux systems comes with the GCC compiler. GCC stands for GNU compiler Collection. We can use GCC compiler to compile the C programs in Linux based systems like Ubuntu, Centos, Debian, etc.

To compile the program using the gcc, Use the following command. 

Note here helloworld.c is our file name. 

The above command will generate a Executable file or Binary file. Which we can run later. As we are working with Linux based system, The default executable file name is a.out 

Check your present working directory for the file named a.out, That is our executable file. 

GCC compiler also have option to specify the resulting executable file.  If you want to give a specific name for your executable file use option -o while compiling the program. 

 

Running the C Program :

Now we got executable file, To run the executable file just type the executable filename, here executable is a.out So we need to run 

Here ./ (back-slash) present directory. or you can use full pathname like /home/venkey/a.out to run your program.

 

Bonus : Few GCC Tips:

There are few Interesting options are available in GCC have a look.

If you know different stages of C program compilation then you might know about preprocessor, translator and the assembler and linker. GCC provides options to stop compilation at above-specified stages.

Recommended :
You can read Different Compilation stages of C program.

Let’s say we have one source file and filename of the source file is prog.c

To get pre-processed code use option -E.

To get translated code use option -S.

To get  Assembled code use option -c (note c is small alphabet)

Here prog.o is object file.
To get the executable file just run the object file.

 

Now we got the executable file a.out you can run this one to see the output.

Also Check:

 

Related Articles :

 

Venkat

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

Leave a Reply