Command-Line
Compilation
Learn how to compile and run C++ programs from the terminal using g++ and clang++: the foundation every developer needs.
What Is Compilation?
Computers don't understand C++ directly. Your processor speaks machine code: raw binary instructions. Compilation is the process of translating your human-readable C++ source code into an executable file the computer can run.
The Build Pipeline
Why the Command Line?
Meet g++ and clang++
g++ (GNU Compiler Collection) and clang++ (LLVM Clang) are the two most widely used C++ compilers. Both accept nearly identical command-line syntax for everyday use.
The Core Command
$ g++ main.cpp
Compile vs. Run
| Compile | Run | |
|---|---|---|
| Command | g++ main.cpp | ./a.out |
| What happens | Translates source to machine code | Executes the machine code |
| When errors appear | Syntax errors, type errors | Runtime errors, logic bugs |
| Output | An executable file | Your program's output |
Step-by-Step Workflow
Essential Compiler Flags
| Flag | Purpose | Example |
|---|---|---|
| -o name | Set output filename | g++ main.cpp -o hello |
| -Wall | Enable all warnings | g++ -Wall main.cpp |
| -std=c++17 | Use C++17 standard | g++ -std=c++17 main.cpp |
| -g | Include debug info | g++ -g main.cpp |
Example 1: Hello World
#include <iostream> int main() { std::cout << "Hello, World!" << std::endl; return 0; }
$ g++ hello.cpp -o hello $ ./hello Hello, World!
Example 2: Warnings and Standards
#include <iostream> int main() { int age; // uninitialized! std::cout << "Age: " << age << std::endl; return 0; }
$ g++ -Wall -std=c++17 age.cpp -o age age.cpp:5: warning: 'age' is used uninitialized
Example 3: Multiple Files
Real projects split code across files. You can list them all in one command:
$ g++ -Wall -std=c++17 main.cpp utils.cpp -o app $ ./app
Reading Compiler Errors
main.cpp:6:18: error: expected ';' after expression cout << "Hi" ^ ;
Why ./ Before the Executable?
On Unix-based systems, the shell only searches directories in your PATH for commands. Your current folder is usually not in the PATH. The ./ prefix explicitly says "look in the current directory."
$ a.out command not found: a.out $ ./a.out Hello, World!
Common Mistakes
Quick Reference Cheat Sheet
| Task | Command |
|---|---|
| Compile (default name) | g++ main.cpp |
| Compile (custom name) | g++ main.cpp -o program |
| Compile with warnings | g++ -Wall main.cpp -o program |
| Compile C++17 | g++ -std=c++17 -Wall main.cpp -o program |
| Run | ./program |
| Multiple files | g++ file1.cpp file2.cpp -o app |
Question 1 of 5
What is the default name of the executable produced by g++ main.cpp?
Question 2 of 5
Which flag tells the compiler to enable all common warnings?
Question 3 of 5
You type a.out and get "command not found." What is the most likely fix?
Question 4 of 5
You edit main.cpp and run ./program but see the old output. What step did you forget?
Question 5 of 5
Which command compiles two source files into an executable named app?