C programming language is a powerful tool to build applications and scripts to automate tasks. Sometimes you may need to run C program in Linux. In this article, we will learn how to run C program in Linux. Every C program needs to be compiled before it is executed. We will use gcc compiler for our article. You are free to use another compiler but please note, different compilers have subtle differences in their compilation and even supported C syntax.
How to Run C Program in Linux
Here are the steps to execute C Program in Linux.
1. Install C Compiler
Open terminal and run the following command to install gcc compiler in Linux.
$ sudo apt install gcc
2. Compile C Program
Let us say you have saved your C program as my_program.c. Run the following command to compile this C program file.
$ gcc -o my_program my_program.c
In the above code, we instruct gcc to compile my_program.c and store the compiled output as my_program, using -o option. If you don’t specify the output filename, it will create a default output file a.out.
3. Execute C Program
Once you have compiled the C program, run the following command to execute it. Please note, you need to execute the compiled code generated in previous step and not .c file which contains source code.
On running the above command, it will show you the program’s output.
That’s it. In this article, we have learnt how to run C Program in Linux. There are a couple of things to keep in mind while doing this. First, different C compilers have minor variations in their interpretation of C source code. So the code that is compiled without errors in one compiler, may give warning in another compiler, and even errors in some other compiler. So you may need to tweak your C program according to the compilers. Nevertheless, most compilers support commonly used elements. Second, you need to run the compiled C object and not source code. If you try running the .c source code file, it will give you an error.