How to Compile C++ Code in macOS ?

Compiling a C++ code means translating the program from the human-readable form (high-level language) to something a machine can “understand” (machine language) so that the program can run on a machine. In this article, we will learn how to compile C++ code in macOS.

C++ Program Compilation in macOS

GNU provides us with 2 compilers: GCC and g++ for compiling codes. We use GCC to compile C language codes and g++ to compile C++ Codes. We prefer to use the g++ compiler because it automatically links object files in the standard (std) C++ libraries. Use the below steps to compile a C++ program on your Mac:

Step 1. Install G++ Compiler in macOS

Before compiling a C++ code in macOS, make sure that the g++ compiler is already installed on your Mac. Run the below command in the terminal to check.

owner@owner:/$ g++

Step 2. Write Your C++ Program

Now, create a program that you want to compile and run named, myProgram.cpp in any text editor of your choice and save it.

myProgram.cpp

C++
// C++ sample program to run

#include <iostream>
using namespace std;

int main()
{
    // print this is my first program
    cout << "This is My First Program";
    return 0;
}

Step 3: Compile Your Code

To compile the above program, open terminal and open the file location where the program is saved. Run the below command to compile the program.

owner@owner:/$ g++ myProgram.cpp -o myProgram

When the above command gets executed it creates an executable file named myProgram.exe. Here, .exe indicates it is an executable file and -o is used to name that executable file as per ouw own choice (here myProgram). It -o is not used then automatically a executable file named a.out is created.

Step 4: Run Your Program

Finally, run the program using the below command in the Terminal.

owner@owner:/$ ./myProgram

Now, you’ve successfully compiled and run a C++ program and it prints the desired output on your macOS system.

Conclusion

Compiling C++ code on macOS is a straightforward process, whether we prefer the command line or an IDE. Understanding the various approaches helps us to choose the method that best suits our workflow and project requirements. By mastering compilation techniques, we can effectively develop and execute C++ applications on our macOS system.


Contact Us