C++ Get Started

To start writing C++ programs, you need two things: a place to write your code (a text editor or an IDE) and a way to turn that code into a program a computer can run (a compiler). This lesson shows you the smallest possible C++ program and explains what each part of it does.

What You Need

C++ code is written in plain text files, usually with a .cpp extension. To turn that text into a runnable program, you need a compiler, such as g++ (part of the GNU Compiler Collection). Many beginners also use an online compiler in a web browser, which requires no installation and is a great way to follow along with this course.

If you want to compile locally, a typical command looks like this:

g++ hello.cpp -o hello
./hello

The first command compiles hello.cpp into a program named hello. The second command runs that program.

Your First Program

Every C++ program needs a starting point. That starting point is a function named main. Here is the classic first program, which prints a short message to the screen:

#include <iostream>
using namespace std;

int main() {
    cout << "Hello World!";
    return 0;
}

Output:

Hello World!

How It Works

  • #include <iostream> tells the compiler to include the input/output library, which gives you tools like cout for printing text.
  • using namespace std; lets you write cout instead of the longer std::cout. It saves typing but is only recommended for small programs and learning.
  • int main() { ... } defines the main function. Every C++ program has exactly one main function, and the program always starts running from here.
  • cout << "Hello World!"; sends the text "Hello World!" to the console using the << insertion operator. Notice the semicolon at the end — every statement in C++ ends with one.
  • return 0; tells the operating system the program finished successfully. The int before main means the function returns a whole number, and 0 conventionally means “no errors”.

A Note on Semicolons

C++ does not care about line breaks or spacing — it cares about semicolons. Each statement must end with ;, or the compiler will report an error. Curly braces { } group statements together, such as everything that belongs inside main.

Next Steps

Now that you can write, compile, and run a basic C++ program, the next lesson looks at C++ syntax in more detail, including how statements and functions are structured.