0
0
CHow-ToBeginner · 3 min read

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 executable output. If omitted, the default executable is a.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 -o option 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

CommandDescription
gcc source.cCompile source.c to default executable a.out
gcc source.c -o myprogCompile source.c to executable named myprog
./a.outRun default executable
./myprogRun named executable
gcc -Wall source.c -o progCompile 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.