Skip to main content
PProfileMatch

C++ Introduction: Syntax, Compiling and Your First Program

ProgrammingLesson 1 of 65 min read

What you'll learn

  • Explain what makes C++ different from interpreted and virtual-machine languages
  • Install a compiler and compile a program with g++
  • Read a basic C++ program: headers, namespaces, main, cout and cin
  • Understand the preprocess, compile and link steps and recognise their errors

On this page

  1. What is C++ and how is it different?
  2. Installing a compiler
  3. Your first C++ program
  4. Compiling and running
  5. Reading input and a tour of the syntax
  6. Common mistakes
  7. How this shows up in interviews and real projects

C++ is a compiled language that gives you direct control over memory and performance, which is why it appears in game engines, browsers, databases, trading systems and embedded devices. That control comes with more responsibility than languages like Python or Java, so it pays to understand exactly how your source code becomes a running program. This lesson walks you from nothing to a working program.

What is C++ and how is it different?

C++ is a statically typed, general-purpose language that supports procedural, object-oriented and generic programming. The big difference from Java or Python is how it runs. A C++ compiler translates your code straight into machine code for your processor, producing a native executable. There is no virtual machine and no garbage collector in between, so programs start fast and run fast, but you must manage resources yourself and you must compile separately for each operating system.

FeatureC++JavaPython
How it runsCompiled to native machine codeCompiled to bytecode, run on the JVMInterpreted
Memory managementManual, with smart pointers to helpGarbage collectedGarbage collected
TypingStaticStaticDynamic
Entry pointint main()public static void mainTop of the script

Installing a compiler

You need a C++ compiler. The most common free options are g++ (part of GCC) and clang++. On Linux, install g++ with your package manager (for example sudo apt install g++ on Debian or Ubuntu). On macOS, run xcode-select --install to get clang. On Windows, install MinGW-w64 (for example through MSYS2) or use Visual Studio's MSVC compiler. Then verify it from a terminal.

Terminal
g++ --version

Output

g++ (GCC) 13.2.0

Your version number and wording will differ, which is fine. Anything from GCC 9 or Clang 10 onward handles the C++17 code in this tutorial.

Your first C++ program

Create a file named hello.cpp and type the following. Unlike Java, the file name does not need to match anything inside it.

hello.cpp
#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

Output

Hello, World!

Here is what each line does:

  • #include <iostream> is a preprocessor directive that pastes in the declarations for input and output streams. Without it, the compiler does not know what cout is.
  • int main() is the entry point. The operating system starts your program here, and the int return value is the exit status. return 0; means success, and for main only, you may omit it.
  • std::cout is the standard output stream. << sends values into it, and you can chain several in one statement.
  • std::endl ends the line and flushes the output. The string "\n" also ends a line and is slightly cheaper.
  • Every statement ends with a semicolon, and blocks are wrapped in braces.

The std:: prefix means "the thing named cout that lives in the standard library namespace std". Namespaces prevent name clashes between libraries. To save typing, beginner examples often add using namespace std; at the top so you can write cout instead of std::cout. That is fine for small programs and the rest of this tutorial does it, but in larger projects and header files prefer writing std:: explicitly.

Compiling and running

Compile with the compiler, naming the output file with -o. The flag -std=c++17 selects the language standard and -Wall -Wextra turn on helpful warnings. Always read the warnings; in C++ many serious bugs show up as warnings first.

Terminal
g++ -std=c++17 -Wall -Wextra hello.cpp -o hello
./hello

Output

Hello, World!

On Windows the executable is hello.exe, and you run it with hello or .\hello. Behind that one command the toolchain does three things.

StageWhat happensTypical errors
Preprocessing#include and #define lines are expanded into plain source textfatal error: foo.h: No such file or directory
CompilingEach .cpp file is checked and translated into an object fileSyntax and type errors such as expected ';'
LinkingObject files and libraries are joined into one executableundefined reference to a function that was declared but never defined

Reading input and a tour of the syntax

cin reads from the keyboard, and >> extracts a value into a variable, converting to the variable's type. Note that cin >> name stops at whitespace, so it reads one word.

greet.cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
    string name;
    int age;
    cout << "Enter your name: ";
    cin >> name;
    cout << "Enter your age: ";
    cin >> age;
    cout << "Hello, " << name << "! Next year you will be " << age + 1 << "." << endl;
    return 0;
}

Output

Enter your name: Asha
Enter your age: 25
Hello, Asha! Next year you will be 26.

In that session the user typed Asha and 25. The next program shows comments, escape sequences and arithmetic output. Notice that 2 * 49.5 is 99.0 as a double, but cout prints it as 99 because it drops trailing zeros by default.

syntax_tour.cpp
#include <iostream>
using namespace std;

int main() {
    // A single-line comment
    /* A block comment
       over two lines */
    cout << "Items: " << 3 << "\n";
    cout << "Price: " << 2 * 49.5 << "\n";
    cout << "Tab\tseparated" << "\n";
    cout << "Quote: \"C++\"" << endl;
    return 0;
}

Output

Items: 3
Price: 99
Tab	separated
Quote: "C++"

Common mistakes

  • Forgetting the include. Using cout without #include <iostream> fails with error: 'cout' was not declared in this scope (GCC adds a note suggesting the missing header).
  • Forgetting `std::` or the using-declaration. The same 'cout' was not declared in this scope error appears when you include the header but write cout without std:: or using namespace std;.
  • Missing semicolon. The compiler reports error: expected ';' before 'return', usually pointing at the line after the real mistake.
  • Using the wrong stream arrows. Writing cout >> x or cin << x produces a long no match for 'operator>>' error. Remember that the arrows point in the direction the data flows: cout << value and cin >> variable.
  • Single quotes for strings. cout << 'Hello'; is a multi-character constant with a warning and prints a number, not text. Use double quotes for strings.
  • Ignoring a linker error. undefined reference to 'add(int, int)' means you declared a function but never defined it, or forgot to compile the file that defines it.

How this shows up in interviews and real projects

Interviewers for C++ roles often start with questions such as "what happens when you compile a C++ program?" and "how is C++ different from Java?", and the compile-and-link pipeline above is the honest answer. In real projects you rarely call g++ by hand; build systems such as CMake or Make run it for you, but the same stages and error types apply. When you are ready, browse open roles to see where C++ is used, then continue to C++ Variables and Data Types.

Try it yourself

Write a program that asks for the price of an item and a quantity, then prints the total cost. Compile it with -Wall -Wextra and run it with a few different inputs, including a decimal price.

Show a hint

Read the price into a double and the quantity into an int, then print price * quantity. Remember #include <iostream>.

Key takeaways

  • C++ compiles straight to native machine code, with no virtual machine or garbage collector.
  • A program goes through preprocessing, compiling and linking, and each stage has its own kind of error.
  • Execution starts at int main(); cout << prints and cin >> reads.
  • std:: marks the standard namespace; using namespace std; is acceptable in small examples only.
  • Compile with g++ -std=c++17 -Wall -Wextra file.cpp -o name and read the warnings.

Test yourself

A trick from this lesson's ride: C++ ships a meal cooked for your kitchen; bytecode ships a recipe any kitchen can cook. Four more tricks like it wait along the route, each followed by a question.

Ride this lesson

Frequently asked questions

What is the difference between C and C++?

C++ began as an extension of C and adds classes and objects, templates, references, the standard library containers such as vector, exceptions and smart pointers. Most C code is also valid C++, but C++ is a much larger language that supports object-oriented and generic programming.

What does #include <iostream> do in C++?

It is a preprocessor directive that inserts the declarations for the standard input and output streams, such as cout and cin, into your file before compilation. Without it the compiler reports that cout was not declared in this scope.

Is C++ hard to learn for beginners?

C++ has a steeper learning curve than Python because you deal with types, compilation and memory directly. Starting with the basics in order, using std::string and std::vector instead of raw arrays, and compiling with warnings on makes it very manageable.