#include <iostream>
int main() {
std::cout << "Hello, World!";
return 0;
}Your First C++ Program: Writing, Compiling, and Running main()
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:
This simple program displays:
Hello, World!Although the program contains only a few lines, each part has a specific purpose.
The basic process is:
C++ Source Code
↓
Compiler
↓
Object Code
↓
Linker
↓
Executable Program
↓
Run
↓
OutputYour First C++ Program
Let's start with the traditional beginner program:
#include <iostream>
int main() {
std::cout << "Hello, World!";
return 0;
}When you run this program, the output is:
Hello, World!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
#include <iostream>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
int main()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:
Program starts
↓
main()
↓
Execute statements
↓
Program endsEvery standard C++ program intended to run as an executable needs a main() function.
Why Does main() Return int?
Our example uses:
int main()The int means that the function returns an integer value to the operating system.
For example:
return 0;The value 0 traditionally indicates that the program completed successfully.
So:
int main()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:
int main() {
}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:
int main() {
std::cout << "Hello";
std::cout << "C++";
}4. Printing Text With std::cout
The following statement displays text:
std::cout << "Hello, World!";std::cout is the standard output stream.
The << operator sends data to the output stream.
For example:
std::cout << "Hello";produces:
HelloYou can print different values as well:
std::cout << 100;Output:
100You can also print multiple pieces of information:
std::cout << "Age: " << 25;Output:
Age: 255. The Semicolon ;
C++ statements normally end with a semicolon.
For example:
std::cout << "Hello";The semicolon tells the compiler that the statement has ended.
This is incorrect:
std::cout << "Hello"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:
return 0;This returns the value 0 from main().
Example:
int main() {
std::cout << "Hello";
return 0;
}In modern C++, reaching the end of main() also implicitly returns 0, so this is valid:
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:
#include <iostream>
int main() {
std::cout << "Hello, World!";
return 0;
}Let's break it into four logical parts:
| Code | Purpose |
|---|---|
#include <iostream> | Provides input/output functionality |
int main() | Program entry point |
std::cout | Displays output |
return 0; | Indicates successful completion |
How to Create a C++ Source File
C++ source files commonly use the .cpp extension.
For example:
main.cppYou can create a file named:
hello.cppThen enter:
#include <iostream>
int main() {
std::cout << "Hello, World!";
return 0;
}Save the file.
Your basic project might look like:
my-first-cpp-program/
└── main.cppCompile 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:
g++ main.cpp -o helloHere:
g++is the C++ compiler command.
main.cppis your source file.
-o hellospecifies the name of the output executable.
After successful compilation, you may have:
main.cpp
helloOn Windows, the executable will normally be:
hello.exeRun the C++ Program on Linux
On Linux or another Unix-like system, run:
./helloYou should see:
Hello, World!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:
hello.exeyou can run it from Command Prompt with:
hello.exeDepending on your terminal, you can also use:
.\hello.exeThe program should display:
Hello, World!Compile and Run With One Command
On Linux or macOS, you can compile and run the program with:
g++ main.cpp -o hello && ./helloThe && means the second command runs only if compilation succeeds.
So the process becomes:
Compile
↓
Compilation successful?
↓
Yes
↓
Run programUsing C++ Standards
C++ has evolved through multiple language standards.
You can tell GCC which standard to use.
For example:
g++ -std=c++17 main.cpp -o helloOr:
g++ -std=c++20 main.cpp -o helloFor newer projects, you may also see:
g++ -std=c++23 main.cpp -o helloThe 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.
#include <iostream>
int main() {
std::cout << "Hello\n";
std::cout << "Welcome to C++\n";
return 0;
}Output:
Hello
Welcome to C++You can also use std::endl:
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.
#include <iostream>
int main() {
std::cout << "Name: " << "Rahul" << "\n";
std::cout << "Age: " << 25 << "\n";
return 0;
}Output:
Name: Rahul
Age: 25The << operator allows several values to be sent to std::cout.
Printing Variables
You can also print variables.
#include <iostream>
int main() {
int age = 25;
std::cout << "Age: " << age << "\n";
return 0;
}Output:
Age: 25Here:
int age = 25;creates an integer variable named age.
Then:
std::cout << age;prints its value.
A Slightly More Interesting First Program
Once the Hello World program works, try this:
#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:
First number: 10
Second number: 20
Sum: 30This 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:
./hellothe operating system loads the executable into memory.
A simplified execution process looks like this:
main.cpp
↓
C++ Compiler
↓
Object Code
↓
Linker
↓
Executable
↓
Operating System
↓
main()
↓
std::cout
↓
Terminal OutputUnderstanding 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:
Source Code
↓
Preprocessing
↓
Compilation
↓
Assembly/Object Code
↓
Linking
↓
ExecutableYou 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:
#include <iostream>
int main() {
std::cout << "Hello"
return 0;
}The semicolon after "Hello" is missing.
The compiler will report an error.
Correct version:
std::cout << "Hello";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:
Compiler Error → Program cannot successfully build
Runtime Error → Program built but has a problem while runningCommon First C++ Program Mistakes
1. Forgetting the #include
Incorrect:
int main() {
std::cout << "Hello";
}The program uses std::cout without including its header.
Correct:
#include <iostream>
int main() {
std::cout << "Hello";
}2. Forgetting the Semicolon
Incorrect:
std::cout << "Hello"Correct:
std::cout << "Hello";3. Misspelling main
Incorrect:
int mian() {
}Correct:
int main() {
}The name main has a special role as the program entry point.
4. Incorrect Capitalization
C++ is case-sensitive.
These are different:
main
Main
MAINSimilarly:
std::coutis not the same as:
std::Cout5. Forgetting Curly Braces
Incorrect:
int main()
std::cout << "Hello";Correct:
int main() {
std::cout << "Hello";
}What Is std::?
You may notice:
std::coutinstead of simply:
coutThe std:: prefix means that cout belongs to the C++ standard namespace.
The standard namespace is called:
stdTherefore:
std::coutmeans that you are referring to the standard library's cout.
For beginners, it is generally a good habit to use:
std::coutrather than immediately introducing:
using namespace std;Can You Write cout Without std::?
You may see tutorials using:
using namespace std;
int main() {
cout << "Hello";
}This can work.
However, beginners should understand that:
coutbelongs to the std namespace.
So this:
std::coutmakes 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:
#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.
#include <iostream>
int main() {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Your age is: " << age << "\n";
return 0;
}Example:
Enter your age: 30
Your age is: 30Here:
std::cinreads 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:
#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:
Enter first number: 15
Enter second number: 25
Sum = 40This 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:
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:
g++ -Wall -Wextra main.cpp -o helloThen run:
./helloUsing 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:
Write Code
↓
Build
↓
Compile + Link
↓
RunC++ Source File vs Executable File
It is important to understand the difference.
Source file
Example:
main.cppThis contains code written by the programmer.
Executable
Example:
helloor:
hello.exeThis is the built program that the operating system can execute.
So:
main.cppis not the same thing as:
hello.exeThe compiler toolchain transforms the source into the executable.
What Happens When You Change the Code?
Suppose your original program is:
std::cout << "Hello, World!";You change it to:
std::cout << "Welcome to C++!";You must build the program again.
For example:
g++ main.cpp -o helloThen:
./helloThe new output will be:
Welcome to C++!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:
I am learning C++Exercise 2: Print Multiple Lines
Create output like:
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:
Length
WidthThen calculate:
Area = Length × WidthExercise 5: Display a Simple Introduction
Create a program that asks for a user's name and age and displays:
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:
1. Write
↓
2. Save
↓
3. Compile
↓
4. Run
↓
5. Check OutputFor example:
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:
#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:
int main()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.
return 0;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:
std::cout
std::cinWhat 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:
g++ main.cpp -o helloThen run it on Linux or macOS with:
./helloWhy does my C++ program not run after I change the code?
You normally need to compile the source code again after making changes:
g++ main.cpp -o helloThen 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:
┌─────────────────┐
│ 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#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 PrepQ: What happens if main() does not explicitly return a value in C++?
Q: What is the performance difference between std::endl and '\n'?
Key Takeaways, Modern Best Practices & Idioms
C++ Best Practices & Production Rules
'\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.