Hello, World
1 min read
Hello, World
Before writing any C++ code, you need a compiler — a program that translates your source files into machine code that the operating system can run.
Installing a compiler
# macOS — Xcode Command Line Tools ships clang++
xcode-select --install
# Ubuntu / Debian
sudo apt install g++ build-essential
# Fedora / RHEL
sudo dnf install gcc-c++
# Windows — install MinGW-w64 from mingw-w64.org, or use WSL
Verify the installation:
g++ --version
# or
clang++ --version
The program
Create a file named hello.cpp:
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Explanation
#include <iostream> — A preprocessor directive that copies in the standard input/output stream library. Without it, std::cout does not exist. Angle brackets mean the header comes from the standard library; quotes ("myfile.h") mean it is a local file.
int main() — The entry point. The OS calls main when your program starts. int is the return type — an integer status code sent back to the shell.
std::cout — The standard character output stream. std is the standard namespace; :: is the scope resolution operator.
<< — The stream insertion operator. It sends the right-hand value into the stream on the left. Multiple << calls can be chained on one line.
std::endl — Inserts a newline and flushes the output buffer. "\n" inserts a newline without flushing and is faster in tight loops.
return 0; — Returns 0 to the shell, the conventional signal for success. Non-zero means error.
Compiling and running
g++ -std=c++17 hello.cpp -o hello
./hello
Output:
Hello, World!
-std=c++17 enables C++17 features. -o hello names the output binary; without it the compiler produces a.out.
Useful compiler flags
# Enable most warnings — use these on every project
g++ -std=c++17 -Wall -Wextra hello.cpp -o hello
# Optimized release build
g++ -std=c++17 -O2 hello.cpp -o hello
# Debug build with memory error detection
g++ -std=c++17 -g -fsanitize=address,undefined hello.cpp -o hello
-Wall -Wextra catch a large class of bugs at compile time. -fsanitize=address,undefined instruments the binary to detect memory errors and undefined behavior at runtime — run your test suite with this on during development.
Learn modern C++ through working code. Each chapter introduces one concept — variables, functions, classes, templates, smart pointers, concurrency — with a clear example, a line-by-line explanation, and notes on how it applies in real programs.
View book →