Subscribe / Unsubscribe Enewsletters | Login | Register

Pencil Banner

How to code using the C programming language in Mac OS X

Lucy Hattersley | May 26, 2016
Mastering the C programming language - a classic code environment used to build software, apps, and whole operating systems - is a great skill, and Mac OS X makes it easy to learn. Here's how to get started

You'll need a good text editor or IDE (Integrated Developer Environment) to write your C programs. TextEdit isn't a good choice because it doesn't use the plain text by default. TextWrangler is a free program from the App Store, or you can downloadSublime Text, which has an indefinite trial mode (this is our current favourite text editor).

How to learn C in Mac OS X: How to create a Hello World program in C

Learn to code using the C programming language on your Mac: Create Hello World program

C differs from other programming languages, like Python, in that you need to compile programs before you can run them. You'll typically do this in C using the command "make". C programs end with the ".c" extension, and you'll run make to build a second file, that is the compiled program. The compiled file is what you run.

You can do all this from the command line, so let's see how to make a traditional "Hello, World!" program.

Open your text editor and save a file called "hello.c" in your Home folder.

Enter the following code:

#import

int main()

{

    printf("Hello, World!\n");

 

    return 0;

}

Note that we use four single spaces ("    ") to indent the "printf" and "return" lines. You can also use a single Tab space, and there are plenty of vibrant arguments as to which is better. My stance is always to use spaces unless I'm working on somebody else's code that uses tabs. What's most important is not to mix and match styles. Either press the Space bar four times or press the Tab key.

  1. With the "hello.c" file saved in your Home folder, it's time to compile it.
  2. Return to Terminal and enter cd ~ to make sure you're working in the Home directory.
  3. Enter make hello and press Return. Note that you don't include the ".c" extension.
  4. Terminal will display "cc     hello.c   -o hello". If it displays any errors, then go back and check your code.
  5. When it compiles, there will be a second file called just "hello" in the home folder.
  6. Enter ./hello to run the hello program. You will see "Hello, World!" at the command line.

This process is how you build and make programs in C, at least when you're starting. You write a C program in a text editor, and then compile it using make, and then run the compiled program to see the result.

Learn to code using the C programming language on your Mac: Run Hello World program

 

Previous Page  1  2  3  Next Page 

Sign up for CIO Asia eNewsletters.