Beginner⏱️ 7 min📘 Topic 2 of 32

⚙️ How to Install a C++ Compiler and Write Your First Program

Install a C++ compiler (g++, clang, MSVC) and run your first program on Windows, macOS or Linux. Step-by-step setup with online alternatives — no excuses to not start.

You only need three things: an editor, a compiler, and a terminal.

🖥️ Pick a setup

Online (easiest, 0-install) — onlinegdb.com, godbolt.org, or replit.com. Write code in the browser, run it instantly.

Windows — install MSYS2 then pacman -S mingw-w64-x86_64-gcc, or use Visual Studio Community.

macOS — install Xcode Command Line Tools: xcode-select --install. You get clang++.

Linux — usually sudo apt install g++ or equivalent.

📝 The 3-step workflow

  1. Write your source file: hello.cpp
  2. Compile: g++ hello.cpp -o hello
  3. Run: ./hello (or hello.exe on Windows)

💡 Recommended editor

VS Code with the C/C++ extension by Microsoft. Free, fast, cross-platform.

💻 Code Examples

Compile and run from terminal

// hello.cpp
#include <iostream>
int main() {
  std::cout << "Hello, C++!\n";
  return 0;
}
Output:
$ g++ hello.cpp -o hello
$ ./hello
Hello, C++!

Enable warnings and modern standard

g++ -std=c++20 -Wall -Wextra hello.cpp -o hello
Output:
Compiles with the C++20 standard and shows all helpful warnings.

⚠️ Common Mistakes

  • Skipping the compile step and trying to 'run' a .cpp file — that's source, not an executable.
  • Editing in Notepad which adds hidden encoding marks — use VS Code or any real code editor.
  • Forgetting the file extension or putting code in a .txt file.
  • Not adding the compiler to PATH on Windows — the terminal won't find g++.

🎯 Interview Questions

Real questions asked at top product and service-based companies.

Q1.What does the `-o` flag mean in `g++ a.cpp -o app`?Beginner
It specifies the OUTPUT filename. Without -o, g++ defaults to producing `a.out` (or `a.exe` on Windows).
Q2.What's the difference between g++ and gcc?Beginner
gcc is the C compiler driver; g++ is the same driver but invokes the C++ language settings and links the C++ standard library automatically. Use g++ for .cpp files.
Q3.What does -std=c++20 do?Intermediate
It tells the compiler which version of the C++ language standard to use. Newer standards (C++17, C++20, C++23) bring more features. Older codebases sometimes pin to older standards for compatibility.
Q4.What is clang and how is it different from g++?Intermediate
clang is a different C++ compiler (LLVM-based) with better error messages and faster compilation in many cases. It's the default on macOS. The standards-compliant code is identical between them.

🧠 Quick Summary

  • Editor + compiler + terminal — that's the whole toolchain.
  • Online compilers are perfect for learning, zero install.
  • g++ on Linux/Windows, clang++ on macOS.
  • Workflow: write → compile (g++) → run (./executable).
  • Use `-std=c++20 -Wall` to enable modern features and warnings.