Topic 5 of 91 1. Introduction to C++ Interactive Tutorial

Your First C++ Program: Writing, Compiling, and Running main()

14 mins read Last updated: 26 Sep 2026 23,900 views

Direct Answer & Core Concept

Writing your first C++ program is an important step when learning C++. The first program is usually small, but it introduces several fundamental ideas: source code, the main() function, statements, headers, compilation, linking, and program execution.

In this tutorial, you will create a simple C++ program, understand every line of the code, compile it with a C++ compiler, run the executable, and learn how common beginner errors can be fixed.

By the end, you will know exactly how a C++ program moves from source code to a running application.

Detailed Explanation & Mechanics

What Is a C++ Program?

A C++ program is a collection of instructions written using the C++ programming language.

For example:

main.cpp
Run Online
#include <iostream>

int main() {
    std::cout << "Hello, World!";
    return 0;
}

This simple program displays:

Although the program contains only a few lines, each part has a specific purpose.

The basic process is:

main.cpp
Run Online
C++ Source Code
↓
Compiler
↓
Object Code
↓
Linker
↓
Executable Program
↓
Run
↓
Output

Your First C++ Program

Let's start with the traditional beginner program:

main.cpp
Run Online
#include <iostream>

int main() {
    std::cout << "Hello, World!";
    return 0;
}

When you run this program, the output is:

This program is often called the Hello World program because it is one of the simplest ways to verify that your C++ compiler and development environment are working.


Understanding the C++ Program Line by Line

Let's examine each part.

1. The #include <iostream> Line

This line includes the C++ standard input/output library.

The iostream header provides functionality for working with input and output streams.

For example, std::cout is provided through this header.

Without including the appropriate header, the compiler may not know about std::cout.


2. The main() Function

The main() function is the entry point of a normal C++ program.

When an executable C++ program starts, execution begins in main().

A simple way to think about it is:

main.cpp
Run Online
Program starts
↓
main()
↓
Execute statements
↓
Program ends

Every standard C++ program intended to run as an executable needs a main() function.


Why Does main() Return int?

Our example uses:

The int means that the function returns an integer value to the operating system.

For example:

The value 0 traditionally indicates that the program completed successfully.

So:

can be understood as:

Start the program with a function named main() that returns an integer status value.


3. Curly Braces { }

The body of the main() function is surrounded by curly braces:

The opening brace:

marks the beginning of the function body.

The closing brace:

marks the end.

Statements placed between these braces are executed when the function runs.

For example:

main.cpp
Run Online
int main() {
    std::cout << "Hello";
    std::cout << "C++";
}

4. Printing Text With std::cout

The following statement displays text:

main.cpp
Run Online
std::cout << "Hello, World!";

std::cout is the standard output stream.

The << operator sends data to the output stream.

For example:

produces:

You can print different values as well:

Output:

You can also print multiple pieces of information:

main.cpp
Run Online
std::cout << "Age: " << 25;

Output:


5. The Semicolon ;

C++ statements normally end with a semicolon.

For example:

The semicolon tells the compiler that the statement has ended.

This is incorrect:

The missing semicolon can produce a compiler error.

A useful beginner rule is:

Most executable statements in C++ end with ;.


6. The return 0; Statement

At the end of main() we have:

This returns the value 0 from main().

Example:

main.cpp
Run Online
int main() {
    std::cout << "Hello";
    return 0;
}

In modern C++, reaching the end of main() also implicitly returns 0, so this is valid:

main.cpp
Run Online
int main() {
    std::cout << "Hello";
}

However, explicitly writing return 0; can be useful for beginners because it makes the return value visible.


Complete First C++ Program

Here is the complete program again:

main.cpp
Run Online
#include <iostream>

int main() {
    std::cout << "Hello, World!";
    return 0;
}

Let's break it into four logical parts:

CodePurpose
#include <iostream>Provides input/output functionality
int main()Program entry point
std::coutDisplays output
return 0;Indicates successful completion

How to Create a C++ Source File

C++ source files commonly use the .cpp extension.

For example:

You can create a file named:

Then enter:

main.cpp
Run Online
#include <iostream>

int main() {
    std::cout << "Hello, World!";
    return 0;
}

Save the file.

Your basic project might look like:

Architecture Diagram
my-first-cpp-program/
└── main.cpp

Compile Your First C++ Program

Writing the source code is only the first step.

A computer cannot directly execute the C++ source code in its original form.

The source code must be compiled.

A C++ compiler translates your source code into machine-readable code and works with the linker to produce an executable program.

Common C++ compilers include:

  • GCC

  • Clang

  • Microsoft Visual C++ (MSVC)


Compile C++ With GCC

If GCC is installed, open a terminal in the directory containing main.cpp.

Run:

Here:

is the C++ compiler command.

is your source file.

specifies the name of the output executable.

After successful compilation, you may have:

On Windows, the executable will normally be:


Run the C++ Program on Linux

On Linux or another Unix-like system, run:

You should see:

The ./ tells the shell to execute the program from the current directory.


Run the C++ Program on Windows

If you compiled the program using a Windows development environment and the executable is called:

you can run it from Command Prompt with:

Depending on your terminal, you can also use:

The program should display:


Compile and Run With One Command

On Linux or macOS, you can compile and run the program with:

main.cpp
Run Online
g++ main.cpp -o hello && ./hello

The && means the second command runs only if compilation succeeds.

So the process becomes:

main.cpp
Run Online
Compile
↓
Compilation successful?
↓
Yes
↓
Run program

Using C++ Standards

C++ has evolved through multiple language standards.

You can tell GCC which standard to use.

For example:

main.cpp
Run Online
g++ -std=c++17 main.cpp -o hello

Or:

main.cpp
Run Online
g++ -std=c++20 main.cpp -o hello

For newer projects, you may also see:

main.cpp
Run Online
g++ -std=c++23 main.cpp -o hello

The exact standard you should choose depends on your project, compiler version, and the features you need.

For a basic Hello World program, almost any modern C++ standard is sufficient.


Adding a New Line to the Output

You can use \n to move the cursor to the next line.

main.cpp
Run Online
#include <iostream>

int main() {
    std::cout << "Hello\n";
    std::cout << "Welcome to C++\n";

    return 0;
}

Output:

You can also use std::endl:

main.cpp
Run Online
std::cout << "Hello" << std::endl;
std::cout << "Welcome to C++" << std::endl;

For basic output, \n is commonly preferred when you only need a newline.


Printing Multiple Values

C++ allows you to combine multiple output operations.

main.cpp
Run Online
#include <iostream>

int main() {
    std::cout << "Name: " << "Rahul" << "\n";
    std::cout << "Age: " << 25 << "\n";

    return 0;
}

Output:

The << operator allows several values to be sent to std::cout.


Printing Variables

You can also print variables.

main.cpp
Run Online
#include <iostream>

int main() {
    int age = 25;

    std::cout << "Age: " << age << "\n";

    return 0;
}

Output:

Here:

creates an integer variable named age.

Then:

prints its value.


A Slightly More Interesting First Program

Once the Hello World program works, try this:

main.cpp
Run Online
#include <iostream>

int main() {
    int firstNumber = 10;
    int secondNumber = 20;

    int sum = firstNumber + secondNumber;

    std::cout << "First number: " << firstNumber << "\n";
    std::cout << "Second number: " << secondNumber << "\n";
    std::cout << "Sum: " << sum << "\n";

    return 0;
}

Output:

main.cpp
Run Online
First number: 10
Second number: 20
Sum: 30

This small program already demonstrates several C++ concepts:

  • Variables

  • Integer data types

  • Arithmetic operators

  • Assignment

  • Output

  • main()

  • Statements


How the C++ Program Actually Runs

When you execute:

the operating system loads the executable into memory.

A simplified execution process looks like this:

main.cpp
Run Online
main.cpp
↓
C++ Compiler
↓
Object Code
↓
Linker
↓
Executable
↓
Operating System
↓
main()
↓
std::cout
↓
Terminal Output

Understanding this flow is useful because later compiler and linker errors will make much more sense.


What Does the Compiler Do?

The compiler analyzes your C++ source code and translates it into lower-level code that can eventually be executed by the computer.

For a simple project, the process can be viewed as:

main.cpp
Run Online
Source Code
↓
Preprocessing
↓
Compilation
↓
Assembly/Object Code
↓
Linking
↓
Executable

You do not normally need to perform every stage manually when learning C++.

The compiler toolchain handles these steps for you.


Compiler Errors vs Program Errors

Beginners often see an error message and are unsure what went wrong.

There are several different types of problems.

Syntax Error

For example:

main.cpp
Run Online
#include <iostream>

int main() {
    std::cout << "Hello"
    return 0;
}

The semicolon after "Hello" is missing.

The compiler will report an error.

Correct version:


Linker Error

A linker error happens after compilation when required pieces cannot be linked together.

These errors are different from ordinary syntax errors.

For simple programs using a normal compiler command, you may encounter linker problems if:

  • required libraries are missing

  • incompatible object files are used

  • the wrong compiler command is used

  • a function is declared but not properly defined


Runtime Error

A runtime error occurs after the program has successfully compiled and started running.

For example, a program might attempt an invalid operation.

The important distinction is:

main.cpp
Run Online
Compiler Error → Program cannot successfully build

Runtime Error → Program built but has a problem while running

Common First C++ Program Mistakes

1. Forgetting the #include

Incorrect:

main.cpp
Run Online
int main() {
    std::cout << "Hello";
}

The program uses std::cout without including its header.

Correct:

main.cpp
Run Online
#include <iostream>

int main() {
    std::cout << "Hello";
}

2. Forgetting the Semicolon

Incorrect:

Correct:


3. Misspelling main

Incorrect:

Correct:

The name main has a special role as the program entry point.


4. Incorrect Capitalization

C++ is case-sensitive.

These are different:

Similarly:

is not the same as:


5. Forgetting Curly Braces

Incorrect:

main.cpp
Run Online
int main()
    std::cout << "Hello";

Correct:

main.cpp
Run Online
int main() {
    std::cout << "Hello";
}

What Is std::?

You may notice:

instead of simply:

The std:: prefix means that cout belongs to the C++ standard namespace.

The standard namespace is called:

Therefore:

means that you are referring to the standard library's cout.

For beginners, it is generally a good habit to use:

rather than immediately introducing:


Can You Write cout Without std::?

You may see tutorials using:

main.cpp
Run Online
using namespace std;

int main() {
    cout << "Hello";
}

This can work.

However, beginners should understand that:

belongs to the std namespace.

So this:

makes the origin of the name explicit.

For small learning examples, either approach may appear, but explicit namespace qualification is often clearer.


A Clean Beginner C++ Program

A simple style to follow is:

main.cpp
Run Online
#include <iostream>

int main() {
    std::cout << "Hello, World!\n";

    return 0;
}

This program is:

  • Easy to read

  • Easy to compile

  • Easy to understand

  • Suitable for testing a C++ installation


First C++ Program Using User Input

After you understand output, you can try keyboard input.

main.cpp
Run Online
#include <iostream>

int main() {
    int age;

    std::cout << "Enter your age: ";
    std::cin >> age;

    std::cout << "Your age is: " << age << "\n";

    return 0;
}

Example:

main.cpp
Run Online
Enter your age: 30
Your age is: 30

Here:

reads input from the user.

The >> operator extracts the entered value.


First C++ Program to Add Two Numbers

You can combine input, variables, arithmetic, and output:

main.cpp
Run Online
#include <iostream>

int main() {
    int a;
    int b;

    std::cout << "Enter first number: ";
    std::cin >> a;

    std::cout << "Enter second number: ";
    std::cin >> b;

    int sum = a + b;

    std::cout << "Sum = " << sum << "\n";

    return 0;
}

Example output:

main.cpp
Run Online
Enter first number: 15
Enter second number: 25
Sum = 40

This is a good next step after Hello World because it introduces interaction with the user.


Compile the Program With Warnings

When learning C++, it is useful to enable compiler warnings.

With GCC:

main.cpp
Run Online
g++ -Wall -Wextra main.cpp -o hello

-Wall enables many useful warnings.

-Wextra enables additional warnings.

Warnings are useful because they can point out suspicious code even when the program technically compiles.

For example:

main.cpp
Run Online
g++ -Wall -Wextra main.cpp -o hello

Then run:


Using an IDE to Run Your First C++ Program

You do not have to compile programs manually from the terminal.

A C++ IDE or editor can provide buttons for:

  • Creating files

  • Writing code

  • Compiling

  • Running

  • Debugging

  • Viewing compiler errors

Common choices include:

  • Visual Studio

  • Visual Studio Code with a C++ toolchain

  • CLion

  • Code::Blocks

The exact steps differ between tools, but the underlying process remains the same:

main.cpp
Run Online
Write Code
↓
Build
↓
Compile + Link
↓
Run

C++ Source File vs Executable File

It is important to understand the difference.

Source file

Example:

This contains code written by the programmer.

Executable

Example:

or:

This is the built program that the operating system can execute.

So:

is not the same thing as:

The compiler toolchain transforms the source into the executable.


What Happens When You Change the Code?

Suppose your original program is:

main.cpp
Run Online
std::cout << "Hello, World!";

You change it to:

main.cpp
Run Online
std::cout << "Welcome to C++!";

You must build the program again.

For example:

Then:

The new output will be:

Changing the source file does not automatically change an already-created executable unless your development environment automatically rebuilds it.


Beginner Practice Exercises

After successfully running Hello World, try these small exercises.

Exercise 1: Change the Message

Print:


Exercise 2: Print Multiple Lines

Create output like:

main.cpp
Run Online
Name: Alex
Age: 20
Language: C++

Exercise 3: Add Two Numbers

Ask the user for two integers and print their sum.


Exercise 4: Calculate a Rectangle's Area

Ask for:

Then calculate:


Exercise 5: Display a Simple Introduction

Create a program that asks for a user's name and age and displays:

main.cpp
Run Online
Hello, Alex!
You are 25 years old.
Welcome to C++.

These exercises help reinforce the basic structure of a C++ program.


A Simple Mental Model for Beginners

Remember these five steps:

main.cpp
Run Online
1. Write
↓
2. Save
↓
3. Compile
↓
4. Run
↓
5. Check Output

For example:

main.cpp
Run Online
main.cpp
↓
g++ main.cpp -o hello
↓
hello
↓
./hello
↓
Hello, World!

Once this process becomes familiar, learning variables, conditions, loops, functions, classes, and other C++ features becomes much easier.


Frequently Asked Questions

What is the first program in C++?

The traditional first C++ program is the Hello World program:

main.cpp
Run Online
#include <iostream>

int main() {
    std::cout << "Hello, World!";
    return 0;
}

It demonstrates the basic structure of a C++ executable program.


Why does C++ use main()?

main() is the standard entry point for a C++ program. Program execution begins there for a normal hosted C++ application.


Is int main() required?

A normal C++ executable program needs a valid main() function. The common form is:

It returns an integer status to the operating system.


What does return 0 mean in C++?

In main(), returning 0 conventionally indicates successful program completion.


What is #include <iostream> used for?

It makes declarations from the standard input/output stream library available to the program. It is needed when using facilities such as:


What compiler should a beginner use?

Popular choices include GCC, Clang, and Microsoft Visual C++. The best choice depends on your operating system and development environment.


How do I compile a C++ program?

With GCC, a basic command is:

Then run it on Linux or macOS with:


Why does my C++ program not run after I change the code?

You normally need to compile the source code again after making changes:

Then execute the newly built program.


Is cout the same as std::cout?

std::cout is the standard library output stream. cout can be used without std:: when a suitable namespace declaration has been introduced, but std::cout is explicit and commonly recommended for clarity.

Suggested Graphic Design

Create a beginner-friendly horizontal infographic titled:

“Your First C++ Program: From Code to Output”

Show this flow:

Architecture Diagram
┌─────────────────┐
│    main.cpp     │
│                 │
│ int main() {    │
│   cout << ...;  │
│ }               │
└────────┬────────┘
↓
┌─────────────────┐
│     Compiler    │
│      g++        │
└────────┬────────┘
↓
┌─────────────────┐
│   Executable    │
│   hello / .exe  │
└────────┬────────┘
↓
┌─────────────────┐
│      Run        │
│    ./hello      │
└────────┬────────┘
↓
┌─────────────────┐
│     Output      │
│ Hello, World!   │
└─────────────────┘

Use small visual icons for source code, compiler, executable, terminal, and output. Keep the design clean and suitable for a programming tutorial website.

Runnable Code Example: Your First C++ Program

C++20 / C++23
main.cpp
Run Online
#include <iostream>

int main(int argc, char* argv[]) {
    std::cout << "========================================
";
    std::cout << "    OperateTools C++ Execution Engine   
";
    std::cout << "========================================
";
    std::cout << "Binary Path: " << argv[0] << "
";
    std::cout << "Total Arguments Received: " << argc << "
";

    for (int i = 1; i < argc; ++i) {
        std::cout << "  Arg [" << i << "]: " << argv[i] << "
";
    }

    std::cout << "Program completed successfully with exit status 0.
";
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: What happens if main() does not explicitly return a value in C++?

A: In ISO C++, reaching the closing brace `}` of `main()` without a return statement implicitly performs `return 0;`.
Q

Q: What is the performance difference between std::endl and '\n'?

A: `\n` writes a newline character to the buffer, whereas `std::endl` writes a newline AND immediately flushes the output stream, which can cause significant I/O slowdowns inside loops.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Use '\n' instead of std::endl for faster output performance.
2. Validate argc bounds before accessing elements in argv.
3. Return non-zero values (like 1 or EXIT_FAILURE) when terminating on critical errors.