C++ Hello World Program
Writing Your First C++ Program
Create a file named hello.cpp
. In C++, the filename can be anything, but it's a good practice to use something meaningful. Here, we use hello.cpp
for our Hello World example.
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Hello, World!
Compiling the Program
Open a terminal or command prompt where your hello.cpp
file is saved and run the following command:
g++ hello.cpp -o hello
What happens during compilation?
The g++
command invokes the GNU Compiler Collection for C++. Here's what it does:
- Reads your
.cpp
source file — written in human-readable C++ code. - Checks for syntax errors and compiles it into machine code.
- Generates an executable file named
hello
.
This executable is now ready to be run on your operating system.
Running the Program
To run the compiled program, use the following command in your terminal:
./hello
What happens during execution?
The system executes the compiled machine code in the hello
binary:
- It loads the program into memory.
- Starts execution from the
main
function. - Prints
Hello, World!
to the console.
Hello, World!
You’ve now compiled and executed your first C++ program — a foundational step in learning the C++ programming language.
Common Issues to Watch For
- Missing semicolons: C++ statements must end with
;
. - Namespace issues: Use
std::
or addusing namespace std;
for convenience. - Missing headers: Functions like
std::cout
require#include <iostream>
.
Comments
Loading comments...