0
0
CppHow-ToBeginner · 4 min read

How to Install g++ on Mac for C++ Development

To install g++ on a Mac, you can install the Xcode Command Line Tools by running xcode-select --install in the Terminal. Alternatively, use Homebrew with brew install gcc to get the latest g++ compiler.
📐

Syntax

To install g++ on Mac, you mainly use two commands depending on the method:

  • Xcode Command Line Tools: xcode-select --install
  • Homebrew package manager: brew install gcc

Here, xcode-select --install installs Apple's developer tools including clang which supports g++ commands. brew install gcc installs GNU's g++ compiler.

bash
xcode-select --install

# or using Homebrew
brew install gcc
💻

Example

This example shows how to compile and run a simple C++ program using g++ after installation.

cpp
#include <iostream>

int main() {
    std::cout << "Hello, g++ on Mac!" << std::endl;
    return 0;
}
Output
Hello, g++ on Mac!
⚠️

Common Pitfalls

Common mistakes when installing or using g++ on Mac include:

  • Not installing Xcode Command Line Tools or Homebrew first.
  • Confusing Apple's clang++ with GNU g++. Both compile C++ but have differences.
  • Using g++ command before installation results in "command not found" error.
  • Not updating Homebrew before installing gcc, which can cause outdated versions.
bash
Wrong:
$ g++ hello.cpp
-bash: g++: command not found

Right:
$ xcode-select --install
# or
$ brew install gcc
$ g++-<version> hello.cpp -o hello
$ ./hello
📊

Quick Reference

CommandPurpose
xcode-select --installInstall Xcode Command Line Tools including clang/g++
brew install gccInstall GNU g++ compiler via Homebrew
g++ filename.cpp -o outputCompile C++ source file to executable
./outputRun the compiled program

Key Takeaways

Install Xcode Command Line Tools with 'xcode-select --install' to get basic g++ support on Mac.
Use Homebrew and 'brew install gcc' for the latest GNU g++ compiler.
Always update Homebrew before installing packages to get the newest versions.
After installation, compile C++ files with 'g++ filename.cpp -o output' and run with './output'.
If 'g++' command is not found, check if the tools are installed correctly.