Compiling C Program in Linux or Unix Based Systems | Compiling C program using GCC

Spread the love

Question : How to compile C program in Linux:

Here the steps to compile the 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 favorite editor. I am using vim here

vim helloworld.c
int main()
    printf(“Hello World n”);
    return 0;

We just created one source file named it as helloworld.c, Let’s try to compile it.
To compile any c program, We use GCC compiler. GCC stands for GNU compiler Collection.

Compiling C Program:

$ gcc helloworld.c

We got executable file and default executable file name under Linux is a.out . see your present working directory for file a.out , If you want to give a specific name for your executable file use option -o while compiling the program.

$ gcc <source_filename> -o <executable_file_name>

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

$ ./a.out

./  means present directory. or you can use full pathname like /home/venkey/a.out to run your program.

That’s it.

GCC Tricks:

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.

gcc –E prog.c –o prog.i

To get translated code use option -S.

$ gcc –S prog.i –o prog.s

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

$ gcc –c prog.s –o prog.o

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

gcc prog.o

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

Related Articles :

Venkatesh Macha

Hi Guys, I am Venkatesh Macha. I am a programmer and an Open Source enthusiast, Presently working as a Software Engineer. Apart from that, I love to explore new technologies and things.

You may also like...

Leave a Reply