Writing your first C++ program is an exciting step into the world of programming! In this tutorial, we’ll go beyond just copying code—you’ll understand what each line means, how to compile on Windows, macOS, or Linux, and how to avoid common beginner mistakes.
Perfect for: Absolute beginners and programmers coming from Python, Java, or JavaScript who want to learn C++.
Step 1: Install a C++ Compiler
To write and run C++ code, you first need a compiler. A compiler translates your C++ code into a language that your computer can understand and execute.
- Windows: We recommend MinGW (via MSYS2) or installing Visual Studio with C++ development tools.
- macOS: Open the Terminal and run
xcode-select --install
to get the Command Line Tools, which include the g++ compiler. - Linux: Open a terminal and run
sudo apt install build-essential
(Debian/Ubuntu) orsudo yum groupinstall 'Development Tools'
(Fedora/CentOS).
Verify your installation by opening a new terminal or command prompt and running:
g++ --version
Step 2: Set Up Your Development Environment
While you can write C++ in a simple text editor, using a code editor or an Integrated Development Environment (IDE) makes the process much smoother. We highly recommend Visual Studio Code (VS Code) with the C/C++ extension for its balance of features and simplicity.
Step 3: The Complete “Hello, World!” Program
Here’s the classic “Hello, World!” program. Create a new file named main.cpp
and copy this code into it. We’ve added comments to explain what each line does.
#include <iostream> // 1. Includes the Input/Output library
int main() { // 2. The main function where the program starts
std::cout << "Hello, World!" << std::endl;// 3. Prints "Hello, World!" to the console
return 0; // 4. Tells the OS the program ran successfully
}
Step 4: Compile and Run Your Program
Open your terminal, navigate to the directory where you saved main.cpp
, and execute the following commands:
- Compile the code:
g++ main.cpp -o hello
This command tells the g++ compiler to take your source code (main.cpp
) and create an executable file namedhello
. - Run the program:
./hello
(on macOS/Linux) orhello.exe
(on Windows).
If everything is correct, you will see the following output in your terminal:
Hello, World!
Tips for Success
- Pay attention to syntax: C++ is case-sensitive and requires semicolons
;
at the end of most lines. - Use comments wisely: Explain the why behind your code, not just the what.
- Practice consistently: Building small projects is the best way to strengthen your understanding of concepts like variables, loops, and functions.