Loading...

First C++ Program: How “Hello World” Works

Write your first C++ program and learn how “Hello World” works, including compilation, execution, and basic program flow.

For beginners learning the C++ language, the most traditional first example is the “Hello, World!” program. This example is the best starting point to understand how a C++ application is compiled and executed. In this article, we’ll walk through how to write a simple console output in C++, how the compilation process works, and what each line of code means, step by step.


1. The First C++ Program

Create a new Console Application in Visual Studio 2022 or any GCC/Clang environment and write the following code:


#include <iostream>   // Library for input/output operations
using namespace std;  // Declares that we’ll use the std namespace

int main() {
    cout << "Hello, World!" << endl; // Prints message to the console
    return 0;                        // Indicates successful program termination
}

When you run this code, the console will display:


Hello, World!

2. Line-by-Line Explanation


3. Compilation and Execution Process

Writing the code is not enough — it needs to be compiled into an executable file. Here’s how the compilation process works:

  1. Source code: Written in a .cpp file.
  2. Compiler: Translates source code into machine code.
  3. Linker: Combines libraries and functions, producing an .exe or .out file.
  4. Execution: The resulting file is run by the operating system.

Simplified compilation flow:


Source Code (.cpp)
     ↓
Compiler (g++)
     ↓
Object File (.o)
     ↓
Linker
     ↓
Executable File (.exe / .out)

4. Running “Hello World” in Visual Studio 2022

  1. Open Visual Studio.
  2. Select “Create New Project” → “Console App” (C++).
  3. Set the project name, e.g., HelloWorld.
  4. Paste the above code into the generated main.cpp file.
  5. Press Ctrl + F5 to build and run the program.
Creating a new C++ console project in Visual Studio 2022 Setting the project name for a C++ console application

If the output window shows Hello, World!, congratulations — your first C++ program ran successfully.


5. Compiling with GCC or Clang (Linux / Windows MSYS2)

If you’re not using Visual Studio, you can do the same from a terminal. Save your code as hello.cpp and run the following command:


g++ -std=c++20 hello.cpp -o hello
./hello

Or, if you’re using Clang:


clang++ -std=c++20 hello.cpp -o hello
./hello

In both cases, the output will be:


Hello, World!

6. Common Errors


7. TL;DR

  • C++ programs start from the main() function.
  • #include <iostream> → adds the input/output library.
  • cout → prints output to the screen.
  • You can run the program using Visual Studio 2022 or GCC.
  • If you see “Hello, World!” as output, your C++ journey has officially begun!

Related Articles