0
0
CHow-ToBeginner · 3 min read

How to Run a C Program in Terminal: Step-by-Step Guide

To run a C program in the terminal, first save your code in a .c file, then compile it using gcc filename.c -o outputname. Finally, execute the program by typing ./outputname in the terminal.
📐

Syntax

Use the gcc command to compile your C program. The basic syntax is:

  • gcc filename.c -o outputname: Compiles filename.c into an executable named outputname.
  • ./outputname: Runs the compiled program in the terminal.
bash
gcc filename.c -o outputname
./outputname
💻

Example

This example shows a simple C program that prints "Hello, World!" and how to compile and run it in the terminal.

c
#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}
Output
Hello, World!
⚠️

Common Pitfalls

Common mistakes include:

  • Not saving the file with a .c extension.
  • Forgetting to compile before running.
  • Trying to run the source file directly instead of the compiled executable.
  • Not having gcc installed or not in your system's PATH.
bash
# Wrong: Trying to run source file directly
./filename.c

# Right: Compile then run
gcc filename.c -o filename
./filename
📊

Quick Reference

CommandDescription
gcc filename.c -o outputnameCompile C source file to executable
./outputnameRun the compiled executable
gcc -Wall filename.c -o outputnameCompile with warnings enabled
gcc filename.cCompile to default a.out executable
./a.outRun default executable if no output name given

Key Takeaways

Always compile your C code with gcc before running it in the terminal.
Use the -o option to name your executable for easier running.
Run the compiled program by prefixing with ./ in the terminal.
Save your source code with a .c extension to avoid confusion.
Check that gcc is installed and accessible in your system PATH.