How to install and run a basic C++ program on an Apple Mac ?

Published: February 13, 2023

Updated: February 18, 2023

Tags: C++; Apple Mac; Protection Status

I recently purchased an Apple MAC studio with M1 core, and wanted to install and execute a basic C++ program. To achieve this, I followed these steps:

Install C and C++ compilers

Unfortunately if you're a Mac user, Gcc is not included by default as a native feature. If you attempt to execute commands from a terminal such as gcc or g++, the following error will appear: "$ gcc -bash: gcc: command not found".

To quickly and easily install C and C++ compilers, all you have to do is open the terminal window in your system and run this command:

xcode-select --install

It's worth noting that it's not necessary to install Xcode completely - only the command line tool will suffice!

Note: gcc and g++ are both compilers used to compile C and C++ programs. GCC stands for the GNU Compiler Collections, which consists of multiple compilers - two being gcc and g++. While gcc is mainly used to compile C programs, g++ is a more advanced compiler that can be utilized for both programming languages - it is an extended version of the traditional compiler designed specifically for use with C language applications.

Create a basic C++ program

Let's get started on our c++ algorithm! We'll call it moonbooks.cpp and begin by launching a new terminal:

touch moonbooks.cpp

Now, let's open the code with an editor (vi for example)

vi moonbooks.cpp

so we can start coding:

#include <iostream>

int main () {
        std::cout << "Hello Moonbooks!";
        return 0;

Now let's make sure to save our work, then exit the file.

Execute your basic C++ program

To compile and create an executable program, simply enter

g++ -o moonbooks moonbooks.cpp

in the command line. Subsequently, to run it just type


In case you're met with a zsh error message that states "command not found: moonbooks" A speedy, short-term fix is to enter the "pwd" command which will give you direct access to the file's executable. Once that's done, simply hit enter!


should print

 Hello Moonbooks!


The resources that helped me are listed below for your convenience: