How to Run a C Program in Terminal
Running a C program in the terminal is a fundamental skill for any programmer, especially those who are new to the world of command-line interfaces. The terminal, also known as the command prompt or shell, is a text-based interface for interacting with a computer. It allows users to execute commands and run programs directly from the keyboard. In this article, we will guide you through the process of compiling and running a C program in the terminal, step by step.
Firstly, you need to have a C compiler installed on your system. The most popular C compiler is GCC (GNU Compiler Collection), which is freely available for most operating systems. To check if GCC is installed on your system, open the terminal and type:
“`
gcc –version
“`
If GCC is installed, you will see the version information. If not, you will need to install it. The installation process varies depending on your operating system. For Linux, you can usually install GCC using the package manager. For example, on Ubuntu, you can install it by running:
“`
sudo apt-get install build-essential
“`
For Windows, you can download and install the MinGW (Minimalist GNU for Windows) package.
Once GCC is installed, you can proceed to write your C program. Create a new file using a text editor, such as nano or vi, and save it with a `.c` extension. For example, `hello.c`. Here is a simple C program that prints “Hello, World!” to the terminal:
“`c
include
int main() {
printf(“Hello, World!”);
return 0;
}
“`
Now, open the terminal and navigate to the directory where you saved the `hello.c` file. You can use the `cd` command to change directories. For example:
“`
cd path/to/directory
“`
Replace `path/to/directory` with the actual path to the directory containing your `hello.c` file.
Next, compile the C program using the `gcc` command. To compile the `hello.c` file, type:
“`
gcc -o hello hello.c
“`
This command tells GCC to compile the `hello.c` file and create an executable named `hello`. The `-o` option specifies the output file name.
Once the compilation is complete, you can run the program by typing:
“`
./hello
“`
This command executes the `hello` executable, and you should see the output “Hello, World!” displayed in the terminal.
Congratulations! You have successfully run a C program in the terminal. By following these steps, you can compile and execute any C program on your system. As you gain more experience, you can explore additional features of the terminal and C programming, such as debugging and more complex program structures.