Course contentsShow
← C
Lesson 58 of 1,2191. FoundationsFree lesson

Naming the output with `-o`

Naming the output with -o

What you'll learn: How to give your compiled program a custom name using a simple compiler flag.

By default, when you tell a compiler like GCC to build your code, it is surprisingly uncreative. If you run gcc hello.c, the compiler produces an executable file named a.out. While this works, it’s not very helpful. If you have five different programs in one folder, they can't all be named a.out without overwriting each other.

To fix this, we use the -o flag, which stands for output.

The "Save As" of Compiling

Think of the -o flag like the "Save As..." dialog in a word processor. Without it, the computer just hits "Save" and uses a generic, messy default name. By adding -o, you are explicitly telling the compiler: "Build this code, but name the finished product this."

The syntax looks like this: gcc source_file.c -o name_you_want

A Practical Example

Let’s say you have a program that calculates the area of a circle. You want the final, runnable file to be named area_calc so you know exactly what it does when you look at your files later.

First, you have your code file, main.c:

#include <stdio.h>

int main() {
    printf("Calculating area...\n");
    return 0;
}

To compile this with a specific name, you would type the following into your terminal:

gcc main.c -o area_calc

After running this command, you won't see an a.out file. Instead, you will see a new file named area_calc. To run it, you would simply type ./area_calc.

Order Matters (Mostly)

A common point of confusion is where the flag goes. The most important rule to remember is that the name you want must immediately follow the -o.

  • Correct: gcc main.c -o my_app
  • Correct: gcc -o my_app main.c
  • Incorrect: gcc -o main.c my_app (This would actually try to overwrite your source code!)

Always treat -o and your chosen name as a pair that shouldn't be separated. By using this simple flag, you keep your workspace organized and your programs easy to identify.

Key takeaway

Use the -o flag followed by a name to tell the compiler exactly what to call your executable file.