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: Compilesfilename.cinto an executable namedoutputname../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
.cextension. - Forgetting to compile before running.
- Trying to run the source file directly instead of the compiled executable.
- Not having
gccinstalled 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
| Command | Description |
|---|---|
| gcc filename.c -o outputname | Compile C source file to executable |
| ./outputname | Run the compiled executable |
| gcc -Wall filename.c -o outputname | Compile with warnings enabled |
| gcc filename.c | Compile to default a.out executable |
| ./a.out | Run 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.