Your First C++ Program
💻 C++Compile and run a C++ program and understand the parts of a minimal file.
0 of 9 completed
C++ is compiled directly to machine code. That makes it fast, and it means you need a compiler before you can run anything.
By the end of this lesson you can:
- Explain the compile step.
- Read a minimal C++ program.
- Compile with g++ or clang++.
The Program
Every C++ program starts at main. #include brings in declarations from the standard library.
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
return 0;
}Compile and Run
Compile to an executable, then run it. Turn on warnings; they catch many bugs before they happen.
g++ -std=c++20 -Wall -Wextra main.cpp -o hello
./helloReading the Pieces
#include <iostream>adds input and output.std::coutwrites to the console.<<sends a value to the stream.return 0tells the operating system the program succeeded.
Tip If the compiler reports an error, read the first one carefully. Later errors are often consequences of the first.
Practice
- Print your name and school on separate lines.
- Explain what return 0 means.
- Compile with -Wall and fix any warning.
Hands-on exercise
Write a program that prints:
1. Your name.
2. Your favourite subject.
3. A closing line.
Each on its own line.
Recap
C++ is compiled, main is the entry point and the standard library is included with headers.
Example
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
return 0;
}
Exercises
Exercise 1. Hello, C++
Easy
Write a program that prints:
1. Your name.
2. Your favourite subject.
3. A closing line.
Each on its own line.
1. Your name.
2. Your favourite subject.
3. A closing line.
Each on its own line.
C++
exercise-1.txt
Output
Expected Output
Three lines printed in order.
Lesson Nav
Course contents
C++ Course
0/9 lessons completed
- 1 Your First C++ Program Tutorial
- 2 Variables, Types and Input Tutorial
- 3 Conditions and Loops Tutorial
- 4 Functions and Parameters Tutorial
- 5 Arrays and Vectors Tutorial
- 6 Pointers and References Tutorial
- 7 Classes and Objects Tutorial
- 8 The STL: Containers and Algorithms Tutorial
- 9 Project: A Console Grade Book Project
Exercises
Exercise 1 Hello, C++