How to Compile a C Program from Command Line Quickly
To compile a C program from the command line, use the
gcc compiler with the syntax gcc source.c -o output. This command compiles source.c into an executable named output.Syntax
The basic command to compile a C program is:
gcc: The GNU C Compiler command.source.c: Your C source file.-o output: Optional flag to name the output executableoutput. If omitted, the default executable isa.out.
bash
gcc source.c -o output
Example
This example shows how to compile and run a simple C program that prints "Hello, World!".
c
#include <stdio.h> int main() { printf("Hello, World!\n"); return 0; }
Output
Hello, World!
Common Pitfalls
Common mistakes when compiling C programs include:
- Forgetting to save the source file before compiling.
- Not specifying the correct file name or path.
- Omitting the
-ooption and expecting a specific executable name. - Trying to run the source file directly without compiling.
bash
/* Wrong: Trying to run source file directly */ ./source.c /* Right: Compile then run */ gcc source.c -o program ./program
Quick Reference
| Command | Description |
|---|---|
| gcc source.c | Compile source.c to default executable a.out |
| gcc source.c -o myprog | Compile source.c to executable named myprog |
| ./a.out | Run default executable |
| ./myprog | Run named executable |
| gcc -Wall source.c -o prog | Compile with all warnings enabled |
Key Takeaways
Use
gcc source.c -o output to compile and name your executable.Always save your source file before compiling to avoid errors.
Run the compiled executable, not the source file.
Use
-Wall flag to see helpful warnings during compilation.If
-o is omitted, the executable is named a.out by default.