01. Setup

Before you can write a C++ program, four things need to be prepared:

  1. A C++ compiler (a program that turns code into a file that can be run).
  2. A code editor.
  3. A terminal for typing commands.
  4. An account on an online judge site for practice.

This chapter sets up all four on Windows 10 or 11.

What the compiler actually does

A computer's processor does not understand the words cout or return. All it understands is binary instructions. The compiler is the translator, and it works in three stages:

Stage Input Output Typical error
preprocessing halo.cpp merged text iostream: No such file (misspelled #include)
compilation that text machine code per file expected ';', not declared in this scope
linking (link) machine code halo.exe undefined reference to 'main'

The first stage copies the contents of the files named in #include into your code. The second stage translates the result into processor instructions. The third stage joins those pieces, including standard library code, into a single .exe file that can run on its own.

Three practical consequences:

  • Typos are found before the program runs. This is a big advantage in a contest: many mistakes that in other languages only show up while the program runs are rejected up front in C++.
  • Changing the code is not enough. The old .exe does not change along with it, so every change must be followed by a recompile.
  • The result is fast. A C++ program runs directly as processor instructions, with no interpreter running alongside it. This is why almost all OSN participants use C++.

1. Install a C++ compiler

C++ is not run directly like a scripting language. The code must first be compiled into a .exe file, and then that file is run. The program that does this is called a compiler.

There are two options. Install only one of them:

Method Compiler Compile command Notes
A g++ from MinGW-w64 g++ same compiler as the online judge and OSN; used throughout the book
B MSVC from Visual Studio cl graphical installer; the commands differ, see the equivalence table in Method B

If you have no specific reason to choose otherwise, pick Method A.

Method A: MinGW-w64 (g++) via winget

The package installed is WinLibs, which is g++ and MinGW-w64 in one package, published by Brecht Sanders. It is installed with winget, the software installer built into Windows 10 and 11. Administrator rights are not required.

  1. Press the Windows key, type PowerShell, and open Windows PowerShell.

  2. Check that winget is available:

     winget --version

    If a version number appears (for example v1.x.y), continue to step 3. If 'winget' is not recognized appears, open the Microsoft Store, search for App Installer, click Install or Update, then close and reopen PowerShell.

  3. Install the compiler. Copy this command exactly as written, including the capital letters and dots:

     winget install --id BrechtSanders.WinLibs.POSIX.UCRT -e --source winget
    • On first use, winget asks Do you agree to all the source agreements terms?. Type Y, then press Enter.
    • The download is several hundred megabytes. Wait until Successfully installed appears.
    • At the end the message Path environment variable modified; restart your shell to use the new value. also appears. It means the compiler folder has been added to PATH, but only windows opened after this point read it.
  4. Close all PowerShell windows, and VS Code too if it is already open. Then open one new PowerShell window.

  5. Check the result:

     g++ --version

    The first line of the output starts with g++ and contains a version number. If it appears, the compiler is ready. Continue to section 2.

If g++ is still not recognized

If step 5 answers 'g++' is not recognized as the name of a cmdlet, function, script file, or operable program, the compiler folder is not on PATH yet. Add it manually:

  1. In PowerShell, find where g++.exe is:

     Get-ChildItem "$env:LOCALAPPDATA\Microsoft\WinGet\Packages" -Recurse -Filter g++.exe | Select-Object -ExpandProperty DirectoryName

    The output is one line ending in \mingw64\bin. Select that line with the mouse and press Ctrl + C to copy it. If there is no output at all, the installation in step 3 did not finish: run step 3 again and read its last message.

  2. Press the Windows key, type environment variables, and open Edit environment variables for your account.

  3. In the top section (User variables), select Path and click Edit....

  4. Click New, paste the folder from step 1 (Ctrl + V), then click OK in every window.

  5. Close all PowerShell and VS Code windows, open a new PowerShell, and run g++ --version again.

To see which g++ is being used, type where.exe g++. In PowerShell, where without .exe is a different command, so the .exe suffix is needed.

Method B: Visual Studio (MSVC)

Visual Studio (not Visual Studio Code) ships Microsoft's own C++ compiler, called MSVC. Its command is cl, not g++.

  1. Open https://visualstudio.microsoft.com, download Visual Studio Community (free), and run its installer.

  2. On the Workloads tab, check Desktop development with C++. Leave the options in the right panel as they are. Click Install and wait until it finishes.

    The same installation can be done from PowerShell:

     winget install --id Microsoft.VisualStudio.Community -e --source winget --override "--add Microsoft.VisualStudio.Workload.NativeDesktop --includeRecommended --passive --norestart"
  3. Press the Windows key, type Developer PowerShell, and open Developer PowerShell for VS.

  4. Type:

     cl

    The output starts with Microsoft (R) C/C++ Optimizing Compiler Version and ends with the line usage: cl [ option... ] filename... [ /link linkoption... ]. If it appears, the compiler is ready.

cl is only recognized in the Developer PowerShell for VS window (or Developer Command Prompt for VS). In a regular PowerShell, cl answers 'cl' is not recognized even when Visual Studio is installed correctly. This is not a fault: Visual Studio deliberately does not add its compiler to the general PATH.

This book writes every compile command in the g++ form. If you use Method B, replace it with the equivalent:

g++ (used in the book) MSVC (Method B)
g++ -std=c++17 -O2 -o halo halo.cpp cl /nologo /std:c++17 /O2 /EHsc halo.cpp
-std=c++17 /std:c++17
-O2 /O2
-o halo not needed: the .exe name is taken from the .cpp file name
(no equivalent) /EHsc: enable standard C++ exception handling
(no equivalent) /nologo: do not print the copyright lines on every compile

Running the program is the same: ./halo. Besides halo.exe, cl also leaves halo.obj; that file can be deleted.

Online judges and the OSN machines use g++, not MSVC. Code that uses g++-specific features such as #include <bits/stdc++.h>, __gcd, or __int128 cannot be compiled with cl. Conversely, code that compiles with cl does not necessarily compile with g++. All code in this book uses only standard C++17, so it compiles with both, but for long-term contest practice Method A is safer.

2. Install a code editor

Use Visual Studio Code (VS Code for short). It is free, runs on Windows, and is used by many professional programmers.

  1. Open https://code.visualstudio.com and download the installer.
  2. Run it. On the Select Additional Tasks screen, check Add to PATH and Register Code as an editor for supported file types.
  3. Open VS Code after the installation finishes.
  4. Install the C++ extension:
    • Click the Extensions icon in the left bar (or Ctrl + Shift + X).
    • Type C++ in the search box.
    • Select the C/C++ extension published by Microsoft.
    • Click Install.

This extension adds syntax highlighting, autocomplete, and error markers directly in .cpp files.

3. Terminal

VS Code has a built-in terminal. Open it with Ctrl + ` (the backtick key, usually below Esc).

This terminal is where you type the two commands used throughout this book: one to compile, and one to run the result.

The VS Code terminal only knows the compilers that were on PATH when VS Code was opened. If the compiler was installed while VS Code was open, close all VS Code windows and open it again.

Method B (Visual Studio) users. A VS Code terminal opened from the Start menu does not know cl. Open VS Code through Developer PowerShell so its terminal knows cl too:

  1. Close all VS Code windows.
  2. Open Developer PowerShell for VS.
  3. Type code, then press Enter.

Do this every time you start studying. To check, type cl in the VS Code terminal; the output must match step 4 of Method B.

4. Test everything

  1. In VS Code choose File → Open Folder..., click New Folder, name it osn, and click Select Folder.

  2. Press Ctrl + N for a new file.

  3. Type:

     #include <iostream>
     using namespace std;
    
     int main() {
         cout << "Halo, OSN!" << endl;
         return 0;
     }
  4. Save it as halo.cpp in that folder (Ctrl + S).

  5. Open the terminal (Ctrl + `) and type these two commands:

     g++ -std=c++17 -O2 -o halo halo.cpp
     ./halo

    Method B users type this:

     cl /nologo /std:c++17 /O2 /EHsc halo.cpp
     ./halo

    cl prints the file name halo.cpp while compiling. That is not an error.

The output:

Halo, OSN!

If that line appears, the whole setup is done.

The first command reads halo.cpp and produces halo.exe. The second command runs halo.exe. In PowerShell, ./halo and .\halo.exe both work. Every time the code is changed, recompile first — running just ./halo will use the old compiled result.

The meaning of the extra flags in the compile command:

Part Meaning
-std=c++17 use the rules of the 2017 version of the C++ language
-O2 optimize the speed of the compiled program
-o halo name the resulting file halo

The c++17 standard is chosen because it is used in many programming contests, including the online judge we will use.

Everyday workflow

Throughout this book you will repeat the same four-step loop. Memorize its shape now so you do not have to think about it later:

  1. Write or change the code in the editor, then save (Ctrl + S).
  2. Compile: g++ -std=c++17 -O2 -o halo halo.cpp (Method B: cl /nologo /std:c++17 /O2 /EHsc halo.cpp)
  3. Run: ./halo
  4. Compare the output with what is expected. If it differs, go back to step 1.

In PowerShell, the up arrow key recalls the previous command, so steps 2 and 3 take just two up arrows and Enter. The two commands can also be combined into one line so that the program runs only if the compile succeeds:

g++ -std=c++17 -O2 -o halo halo.cpp; if ($?) { ./halo }

The same form for Method B:

cl /nologo /std:c++17 /O2 /EHsc halo.cpp; if ($?) { ./halo }

The most common mistake in the first week: changing the code, forgetting to compile, then being confused because the output did not change. If the result seems to "refuse to change", first check whether step 2 was actually run and did not show an error message.

Giving input from a file

Starting from Chapter 03, programs read input. Retyping the same input every time you test is tiring and error-prone. Instead, save the input in a text file, for example masukan.txt ("input.txt"), and pipe it into the program.

In PowerShell:

Get-Content masukan.txt | ./halo

In Command Prompt (cmd), a shorter form also works:

halo.exe < masukan.txt

This is exactly what an online judge does with your program: input comes from a file, not from a human typing. Getting used to it from now on makes testing edge cases in Chapter 10 much faster.

5. Register on an online judge

In OSN, answers are submitted to a judging program: it runs your code with many input files, compares your output with the correct answers, and then gives a score. Practicing on a similar system from the start makes the format of OSN problems feel normal.

Two options commonly used by Indonesian students:

  • TLX (https://tlx.toki.id) — run by TOKI, contains an archive of OSN problems and practice in Indonesian.
  • Codeforces (https://codeforces.com) — in English, with a very large number of problems and regular contests.

Create an account on one of them now. Starting from Part 2, some homework asks you to submit answers there, not just run them on your own computer.

Programs for an online judge read from standard input and write to standard output — there must be no prompts like Masukkan angka: ("Enter a number: ") unless the problem asks for it. Chapter 03 covers this rule in detail.

If something fails

Symptom Most common cause
'winget' is not recognized App Installer is not installed or not updated from the Microsoft Store
'g++' is not recognized PATH does not yet contain the compiler folder, or the terminal window has not been reopened; see "If g++ is still not recognized"
g++ works in PowerShell but not in the VS Code terminal VS Code was already open when the compiler was installed; close all VS Code windows and open it again
'cl' is not recognized the terminal is not Developer PowerShell for VS, or VS Code was not opened from it
cl gives warning C4530 about an exception handler the /EHsc flag was left out
undefined reference to 'main' the main function is misspelled, or the file being compiled is not the intended one
No such file or directory when compiling wrong file name, or the terminal is in a different folder
./halo is not recognized the compile failed, so halo.exe does not exist yet
Permission denied when compiling the old halo.exe is still running in another window
output does not change after editing the code the file has not been saved, or has not been recompiled

To check which folder the terminal is in, type pwd. To see the folder's contents, type ls. If the .cpp file you want to compile does not appear in the ls listing, the terminal is in the wrong folder — move with cd folder-name, or reopen the folder through File → Open Folder... in VS Code.

When asking for help — from a teacher, a friend, or a forum — include three things: the command you typed, the complete error message (copied as-is, not summarized), and the code in question. An error message summarized as "the error is something like that" makes a problem that is actually trivial impossible for anyone else to guess.

OSN tips

This chapter ends with one computer ready to use. This section explains what that readiness is for: the shape of the contest, how your program is judged, and the habits that separate participants who advance from those who do not.

Selection happens in stages. OSN in Informatics filters from the school level to the regency/city level, then the province, then the national level. The rules of each level — number of problems, time allowed, programming languages permitted — are set again every year by the organizers, so the exact figures must be read from the official announcement for the current year, not from stories told by older students. What does not change is the shape of the problems: a program that reads standard input, writes standard output, and is judged automatically.

Judging is done by a machine, not a human. Your program is run against a set of test files that you do not see. The result is a verdict:

Verdict Meaning
Accepted the output matches for all test files
Wrong Answer some output does not match, even by one character
Time Limit Exceeded the program is correct but too slow
Runtime Error the program stopped on its own: division by zero, index outside the array, exit code other than 0
Compile Error the code cannot be compiled on the judging machine

Three consequences are felt right away from Chapter 02:

  • Output must be exact. One wrong capital letter, one extra space, or one lead-in sentence like Masukkan n: ("Enter n: ") is enough to get a correct answer judged Wrong Answer.
  • Speed is part of correctness. A program that is correct but slow gets no points. Chapter 10 covers how to estimate speed before the code is written.
  • Compile on your computer first. A Compile Error on the online judge is zero points for a problem that may already be correct. That is why the command g++ -std=c++17 -O2 in this chapter is used as-is: it is the same one used by the judging machine. Method B users should stick to standard C++17 features, because the code is judged with g++.

Points are often awarded in stages. Many OSN problems are divided into several subtasks with different constraints — for example the first subtask guarantees n ≤ 100, and the last subtask allows n ≤ 1,000,000. A slow program that is correct still earns the points from the subtasks with small constraints. That is why the simplest correct answer is always worth submitting first, and only then improved. This book trains that order starting from Part 3.

Habits to build from now on.

  • Keep every practice program; do not overwrite it. A folder with a hundred old programs is study material; a folder with one a.cpp file that keeps getting overwritten leaves nothing behind.
  • Test with input files, not by retyping numbers every time. The Get-Content masukan.txt | ./halo method above is exactly how the judge runs your program.
  • Regular practice beats cramming. One hour every day gives far better results than seven hours once a week, because what is being trained is the speed of recognizing problem patterns.
  • Write down every mistake that costs you more than ten minutes. Your own list of mistakes is far more useful than a list of general tips.

Do not memorize other people's solution code. What OSN judges is the ability to derive a solution from a problem you have never seen, and OSN problems are deliberately designed not to be the same as the previous year's problems. Memorized code stops being useful at the first problem that is slightly different.

Summary

  • C++ must first be compiled into a .exe, and then run. Every code change means recompiling.
  • The two commands used throughout the book: g++ -std=c++17 -O2 -o halo halo.cpp then ./halo. With Visual Studio, the compile command is cl /nologo /std:c++17 /O2 /EHsc halo.cpp, run from Developer PowerShell for VS.
  • -std=c++17 sets the language version, -O2 speeds up the resulting program, -o names the output file.
  • Test input should be saved in a file and piped in with Get-Content masukan.txt | ./halo, the same way an online judge runs your program.
  • Programs for an online judge must not print lead-in sentences.

The next chapter writes the first C++ program and dissects every line of it.