gcc -o Option

The -o option in gcc specifies the name of the output file when compiling C and C++ programs. Without this option, gcc creates a default executable named a.out.

Syntax

gcc -o outputname sourcefile.c

-o Option Details

  • Purpose: Specify the name of the output executable file
  • Default: Without -o, gcc creates "a.out" as the executable name
  • Usage: Can be used with single or multiple source files
  • Position: Can appear anywhere in the command line

Description

The -o option allows you to control the name of the compiled executable. This is essential for creating meaningful program names and organizing your compiled binaries.

Key behaviors:

  • Specifies the output file name for the final executable
  • Overwrites existing files with the same name
  • Can include path information to place executable in specific directory
  • Works with all compilation stages (compile, assemble, link)

Common Examples

Command Description Output File
gcc hello.c Default compilation a.out
gcc -o hello hello.c Named executable hello
gcc -o myprogram main.c utils.c Multiple files myprogram
gcc -o bin/program source.c Output to directory bin/program

Detailed Examples

Basic compilation with custom name

gcc -o hello hello.c
./hello

Compiles hello.c into an executable named "hello" and runs it

Multiple source files

gcc -o calculator main.c math.c input.c
./calculator

Compiles multiple C files into a single executable

Output to specific directory

mkdir bin
gcc -o bin/myprogram source.c
./bin/myprogram

Creates executable in the bin directory

Combining with other options

gcc -o debug_program -g -Wall program.c
gdb ./debug_program

Compiles with debugging info and warnings, then debugs

C++ compilation

gcc -o cpp_program program.cpp -lstdc++
./cpp_program

Compiles C++ code with custom executable name

Best Practices

  • Meaningful Names: Use descriptive names for executables
  • No Extensions: Linux executables typically don't have extensions
  • Directory Organization: Use bin/ or build/ directories for executables
  • Version Numbers: Include version in name for multiple versions
  • Avoid Conflicts: Don't name executables same as system commands

⚠️ Common Mistakes

  • Missing -o: Forgetting -o creates default "a.out" file
  • Wrong Order: -o must be followed immediately by the output name
  • Overwriting: -o will overwrite existing files without warning
  • Path Issues: Ensure target directory exists when using paths
  • Permissions: Check write permissions for output directory

See also