How to Compile a C File on Mac

Mehvish Ashiq Feb 02, 2024
How to Compile a C File on Mac

This article shows how to compile a .c file on macOS and guides the requirements for successfully executing the .c file.

Compile a .c File on Mac Operating System

Compiling a .c file on the macOS is very simple and can be done as follows.

gcc -o program program.c

Further, we run the as given below to execute the executable file.

./program

But having the right tools to execute the .c file is most important. There are two ways to get the right tools for compiling the .c code on macOS.

Method 1:

  1. Write and save your code as a program.c.

  2. Now, we need a compiler to compile the .c code. Navigate to the App Store and install the XCode and the development tools.

  3. Install the command-line tools in mac Terminal.

  4. Use xcode-select --install to install command-line tools.

  5. Once we are done with this, the easiest way is to get the advantage of the Xcode IDE or can use gcc as given above. We can also use the clang (clang LLVM compiler) instead of the gcc if we use the latest version of macOS X.

    clang program.c -o program
    
  6. Lastly, execute the program as follows.

    ./program
    

Method 2:

  1. Install the gcc compiler.

  2. Make sure you are in the file’s directory first.

    cd directory/path/to/file
    
  3. Compile the code as mentioned below.

    gcc program.c -o program
    
  4. Execute the program from the terminal as follows.

    ./program
    

You can dig more about C compilers for macOS here.

Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook