Chapter 2 of 23

Setting Up Your C++ Development Environment

Install GCC/G++ on Windows, macOS, and Linux, configure VS Code for C++ development, and learn essential compiler flags for writing better code.

Meritshot10 min read
C++SetupGCCVS CodeCompilerEnvironment
All C++ Chapters

Setting Up Your C++ Development Environment

Before you can write and run C++ programs, you need two things: a compiler (the tool that translates your code into an executable) and an editor (where you write the code). This chapter walks you through both, on all three major operating systems, so that by the end you will have a fully working C++ environment ready for everything else in this series.

A well-configured environment does more than just run code — it highlights errors as you type, auto-completes standard library functions, formats your code consistently, and warns you about subtle bugs before they become runtime crashes. Setting this up once pays dividends for every program you write afterwards.


The Compiler: GCC and G++

GCC (GNU Compiler Collection) is the most widely used open-source compiler suite in the world. It includes:

  • gcc — compiles C code
  • g++ — compiles C++ code (and links the C++ standard library automatically)

Both are free, maintained by thousands of contributors, and available on every major platform. When you submit code to competitive programming judges or deploy to Linux servers, GCC is almost certainly what runs your code.

An alternative is Clang/LLVM, which produces excellent diagnostics (error messages) and is the default compiler on macOS. It is fully compatible with GCC flags and C++ standards. For this series we use G++ but the commands are identical for Clang — just replace g++ with clang++.


Installing on Windows

Windows does not ship with a C++ compiler. You have two good options:

MSYS2 is a Unix-like environment for Windows that gives you a proper package manager and up-to-date GCC builds.

  1. Go to msys2.org and download the installer.
  2. Run the installer and accept the defaults. It installs to C:\msys64 by default.
  3. Open the MSYS2 UCRT64 terminal from the Start menu.
  4. Update the package database:
pacman -Syu
  1. Close the terminal if prompted, reopen it, and run:
pacman -Su
  1. Install GCC:
pacman -S mingw-w64-ucrt-x86_64-gcc
  1. Add C:\msys64\ucrt64\bin to your Windows PATH environment variable:

    • Search "Environment Variables" in the Start menu.
    • Under "System variables," select Path and click Edit.
    • Add C:\msys64\ucrt64\bin as a new entry.
    • Click OK on all dialogs.
  2. Open a new Command Prompt (not MSYS2) and verify:

g++ --version

You should see something like g++ (GCC) 13.x.x.

Option B: MinGW-w64 Standalone

If MSYS2 feels heavy, download the MinGW-w64 standalone installer from winlibs.com. Choose the latest GCC with UCRT runtime for 64-bit Windows. Extract the archive (e.g., to C:\mingw64) and add C:\mingw64\bin to PATH following the same steps as above.


Installing on macOS

macOS ships with Apple Clang, but the easiest way to get a full development toolchain (including g++) is via Xcode Command Line Tools.

Open the Terminal app and run:

xcode-select --install

A dialog box will appear asking you to install the command line developer tools. Click Install and wait (it downloads roughly 1 GB). Once finished, verify:

g++ --version

On macOS, g++ is actually an alias for Apple Clang, which is compatible with all the flags and standards we use. If you want the genuine GCC (e.g., for OpenMP support), install it via Homebrew:

brew install gcc

This installs gcc-13 (version-suffixed) alongside the system alias.


Installing on Linux

Linux is the natural home for GCC and installing it takes a single command.

Ubuntu / Debian / Linux Mint (apt)

sudo apt update
sudo apt install build-essential

build-essential is a meta-package that installs gcc, g++, make, and other common build tools in one shot.

Fedora / RHEL / CentOS (dnf/yum)

sudo dnf groupinstall "Development Tools"

Arch Linux (pacman)

sudo pacman -S base-devel

After installation:

g++ --version

Installing VS Code and the C/C++ Extension

Visual Studio Code is a free, lightweight editor from Microsoft that works identically on all three platforms. It is not an IDE in the traditional sense — it is an editor you extend with plugins.

  1. Download VS Code from code.visualstudio.com and install it.
  2. Open VS Code.
  3. Press Ctrl+Shift+X (Windows/Linux) or Cmd+Shift+X (macOS) to open the Extensions panel.
  4. Search for C/C++ (publisher: Microsoft) and click Install.
  5. Optionally, also install C/C++ Extension Pack which bundles the core extension with CMake support and other useful tools.

The C/C++ extension provides:

  • IntelliSense — auto-completion, hover docs, and parameter hints for standard library functions.
  • Syntax highlighting for C++ keywords, types, and string literals.
  • Error squiggles — red underlines for syntax errors without compiling.
  • Go to DefinitionF12 jumps to where a function or variable is declared.
  • Debugger integration — set breakpoints and step through code line by line.

Compiling and Running from the Terminal

Once GCC and VS Code are set up, let us compile a real program. Create a folder for your C++ work, for example ~/cpp-practice/, and inside it create hello.cpp:

#include <iostream>

int main() {
    std::cout << "Hello from the terminal!" << std::endl;
    return 0;
}

Open VS Code's integrated terminal (Ctrl+`` or Cmd+`` ) and run:

g++ -std=c++17 -o hello hello.cpp

Then execute the program:

./hello          // macOS / Linux
hello.exe        // Windows Command Prompt

You should see:

Hello from the terminal!

Breaking Down the Compile Command

FlagMeaning
g++Invoke the G++ compiler/linker
-std=c++17Use the C++17 standard (recommended baseline for modern C++)
-o helloName the output executable hello (without this, the default is a.out on Linux/macOS)
hello.cppThe source file to compile

Essential Compiler Flags

Professional C++ developers never compile without at least a few extra flags. Here are the most important ones:

FlagPurpose
-WallEnable all common warnings (unused variables, implicit conversions, etc.)
-WextraEnable extra warnings beyond -Wall
-WerrorTreat warnings as errors — forces you to fix them
-O0No optimisation (default); easiest for debugging
-O1Basic optimisations
-O2Recommended for production builds; safe, significant speed gains
-O3Aggressive optimisations; occasionally changes floating-point behaviour
-gInclude debugging symbols (needed for GDB/LLDB step-through debugging)
-fsanitize=addressAddressSanitizer — detects buffer overflows and use-after-free at runtime
-fsanitize=undefinedUndefinedBehaviorSanitizer — catches integer overflow, null dereference, etc.

A typical development build command:

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

A typical competitive programming build (speed matters):

g++ -std=c++17 -O2 -o solution solution.cpp

A thorough correctness-checking build (great for catching bugs during development):

g++ -std=c++17 -Wall -Wextra -g -fsanitize=address,undefined -o hello hello.cpp

Configuring VS Code Tasks for One-Click Compilation

Instead of typing the compile command every time, you can create a VS Code task that runs it with a keyboard shortcut.

  1. In VS Code, open the Command Palette (Ctrl+Shift+P / Cmd+Shift+P).
  2. Type "Tasks: Configure Default Build Task" and select it.
  3. Choose "Create tasks.json from template" → "Others."
  4. Replace the generated content with:
// .vscode/tasks.json
// (Note: this is JSON, not C++ — shown in a code block for formatting)
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Build C++",
            "type": "shell",
            "command": "g++",
            "args": [
                "-std=c++17",
                "-Wall",
                "-Wextra",
                "-g",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}",
                "${file}"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "problemMatcher": ["$gcc"]
        }
    ]
}

Now press Ctrl+Shift+B (or Cmd+Shift+B on macOS) to compile the currently open .cpp file. Errors and warnings appear in VS Code's Problems panel.


Online Compilers for Quick Practice

When you are on a slow internet connection, away from your laptop, or want to quickly test a snippet, online compilers are invaluable.

Compiler Explorer (godbolt.org)

The most powerful option. You can:

  • Select any GCC, Clang, or MSVC version.
  • Add custom flags.
  • See the generated assembly output side by side with your C++ source.
  • Share links to your code snippets with others.

This is the tool to use when you want to understand how the compiler optimises your code — a key skill for competitive programming and systems work.

Replit

replit.com gives you a full Linux environment in the browser, complete with a file system, terminal, and editor. You can write multi-file projects, install packages, and collaborate in real time. Replit's free tier is sufficient for all exercises in this series.

OnlineGDB

onlinegdb.com offers a browser-based GDB debugger, so you can set breakpoints and inspect variables without installing anything locally. Useful for beginners debugging their first programs.

Codeforces / LeetCode In-Browser Editors

Both platforms allow you to write, compile, and submit C++ directly in the browser. They use server-side GCC, so the environment is identical to what judges use — ideal for practising under competition conditions.


Common Pitfalls

Wrong PATH on Windows. If the terminal says 'g++' is not recognized as an internal or external command, the MSYS2/MinGW bin directory is not in your PATH. Double-check the path you added and make sure you opened a new terminal window after editing the environment variable.

Using -std=c++17 vs -std=gnu++17. The gnu++ variants enable GCC-specific extensions that are not part of the standard. For portability and to write standard-compliant code, prefer -std=c++17.

Forgetting -o and overwriting a.out. If you compile multiple programs without -o, each compilation overwrites the same a.out. Always name your output explicitly to avoid confusion.

Compiling .c files with g++. G++ will compile .c files as C++, which may cause subtle errors if the file uses C-specific patterns. Use gcc for C and g++ for C++.

Running the old binary after editing. VS Code does not automatically recompile when you save. Always run the build task (Ctrl+Shift+B) before running the program, or add a combined build-and-run shell alias.

Sanitizers in production. -fsanitize=address,undefined adds significant runtime overhead (2–10x slower). Never use sanitizers in performance-critical or production builds — only during development and testing.


Practice Exercises

  1. Install GCC/G++ on your machine following the instructions for your operating system. Run g++ --version and note the version number.

  2. Create a file info.cpp that prints your name, operating system, and GCC version (as string literals you type manually). Compile it with -Wall -Wextra and fix any warnings.

  3. Compile the Hello World program without the -o flag. What is the name of the output file? Run it.

  4. Add a deliberate mistake to hello.cpp — remove one semicolon. Compile with -Wall and read the error message carefully. Then fix it.

  5. Try compiling with -fsanitize=address,undefined and run the resulting binary. Notice the output is identical for a correct program. Now introduce a buffer overrun (declare int arr[3] and write to arr[5]) and observe what the sanitizer reports.

  6. Visit Compiler Explorer, paste the Hello World program, and compare the assembly output with -O0 and -O2. Note which instructions disappear with optimisation.


Summary

  • GCC/G++ is the standard open-source C++ compiler available on Windows (via MSYS2/MinGW), macOS (Xcode tools), and Linux (build-essential / Development Tools).
  • The basic compile command is g++ -std=c++17 -o output source.cpp.
  • VS Code with the Microsoft C/C++ extension provides IntelliSense, error squiggles, and debugger integration.
  • Add -Wall -Wextra during development to catch common bugs early.
  • Add -O2 for production/competitive programming builds.
  • Add -fsanitize=address,undefined to catch memory and undefined-behaviour bugs during testing.
  • Online tools like Compiler Explorer, Replit, and OnlineGDB let you practise without any local setup.
  • Always name your output with -o to avoid overwriting a.out accidentally.