New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› C++› Your First C++ Program

Your First C++ Program

💻 C++

Compile and run a C++ program and understand the parts of a minimal file.

Lesson 1 of 9 Tutorial
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
./hello

Reading the Pieces

  • #include <iostream> adds input and output.
  • std::cout writes to the console.
  • << sends a value to the stream.
  • return 0 tells 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

  1. Print your name and school on separate lines.
  2. Explain what return 0 means.
  3. 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.
C++ exercise-1.txt
Expected Output
Three lines printed in order.

Lesson Nav

Lesson sections